コード例 #1
0
ファイル: Delta_F_up.java プロジェクト: HelioScan/HelioScan
  public void run(String arg) {
    ImagePlus imp = WindowManager.getCurrentImage();
    if (imp == null) {
      IJ.noImage();
      return;
    }

    ImageStack stack1 = imp.getStack();
    String fileName = imp.getTitle();
    int endslice = stack1.getSize();

    ImagePlus imp2 = duplicateStack(imp);
    imp2.show();
    String duplicateName = imp2.getTitle();
    // IJ.showMessage("Box",fileName);
    ImageStack stack2 = imp2.getStack();
    stack1.deleteSlice(1);
    stack2.deleteSlice(endslice);

    String calculatorstring =
        ("image1='"
            + fileName
            + "' operation=Subtract image2="
            + imp2.getTitle()
            + " create stack");

    IJ.run("Image Calculator...", calculatorstring);
    ImagePlus imp3 = WindowManager.getCurrentImage();
    imp3.setTitle(fileName + " DeltaF up");
    imp2.getWindow().close();
    imp.getWindow().close();
  }
コード例 #2
0
ファイル: Bleach_.java プロジェクト: HelioScan/HelioScan
  public void run(String arg) {
    int[] wList = WindowManager.getIDList();
    if (wList == null) {
      IJ.error("No images are open.");
      return;
    }

    double thalf = 0.5;
    boolean keep;

    GenericDialog gd = new GenericDialog("Bleach correction");

    gd.addNumericField("t½:", thalf, 1);
    gd.addCheckbox("Keep source stack:", true);
    gd.showDialog();
    if (gd.wasCanceled()) return;

    long start = System.currentTimeMillis();
    thalf = gd.getNextNumber();
    keep = gd.getNextBoolean();
    if (keep) IJ.run("Duplicate...", "title='Bleach corrected' duplicate");
    ImagePlus imp1 = WindowManager.getCurrentImage();
    int d1 = imp1.getStackSize();
    double v1, v2;
    int width = imp1.getWidth();
    int height = imp1.getHeight();
    ImageProcessor ip1, ip2, ip3;

    int slices = imp1.getStackSize();
    ImageStack stack1 = imp1.getStack();
    ImageStack stack2 = imp1.getStack();
    int currentSlice = imp1.getCurrentSlice();

    for (int n = 1; n <= slices; n++) {
      ip1 = stack1.getProcessor(n);
      ip3 = stack1.getProcessor(1);
      ip2 = stack2.getProcessor(n);
      for (int x = 0; x < width; x++) {
        for (int y = 0; y < height; y++) {
          v1 = ip1.getPixelValue(x, y);
          v2 = ip3.getPixelValue(x, y);

          // =B8/(EXP(-C$7*A8))
          v1 = (v1 / Math.exp(-n * thalf));
          ip2.putPixelValue(x, y, v1);
        }
      }
      IJ.showProgress((double) n / slices);
      IJ.showStatus(n + "/" + slices);
    }

    // stack2.show();
    imp1.updateAndDraw();
  }
コード例 #3
0
ファイル: ImageJ.java プロジェクト: Jondeen/imagej1
 /** Quit using a separate thread, hopefully avoiding thread deadlocks. */
 public void run() {
   quitting = true;
   boolean changes = false;
   int[] wList = WindowManager.getIDList();
   if (wList != null) {
     for (int i = 0; i < wList.length; i++) {
       ImagePlus imp = WindowManager.getImage(wList[i]);
       if (imp != null && imp.changes == true) {
         changes = true;
         break;
       }
     }
   }
   Frame[] frames = WindowManager.getNonImageWindows();
   if (frames != null) {
     for (int i = 0; i < frames.length; i++) {
       if (frames[i] != null && (frames[i] instanceof Editor)) {
         if (((Editor) frames[i]).fileChanged()) {
           changes = true;
           break;
         }
       }
     }
   }
   if (windowClosed
       && !changes
       && Menus.window.getItemCount() > Menus.WINDOW_MENU_ITEMS
       && !(IJ.macroRunning() && WindowManager.getImageCount() == 0)) {
     GenericDialog gd = new GenericDialog("ImageJ", this);
     gd.addMessage("Are you sure you want to quit ImageJ?");
     gd.showDialog();
     quitting = !gd.wasCanceled();
     windowClosed = false;
   }
   if (!quitting) return;
   if (!WindowManager.closeAllWindows()) {
     quitting = false;
     return;
   }
   // IJ.log("savePreferences");
   if (applet == null) {
     saveWindowLocations();
     Prefs.savePreferences();
   }
   IJ.cleanup();
   // setVisible(false);
   // IJ.log("dispose");
   dispose();
   if (exitWhenQuitting) System.exit(0);
 }
コード例 #4
0
ファイル: ImageJ.java プロジェクト: chrisp87/ImageJA
 /** Handles CheckboxMenuItem state changes. */
 public void itemStateChanged(ItemEvent e) {
   MenuItem item = (MenuItem) e.getSource();
   MenuComponent parent = (MenuComponent) item.getParent();
   String cmd = e.getItem().toString();
   if ((Menu) parent == Menus.window) WindowManager.activateWindow(cmd, item);
   else doCommand(cmd);
 }
コード例 #5
0
ファイル: Channels.java プロジェクト: hellotod/HadoopLung
  public Channels() {
    super("Channels");
    if (instance != null) {
      instance.toFront();
      return;
    }
    WindowManager.addWindow(this);
    instance = this;
    GridBagLayout gridbag = new GridBagLayout();
    GridBagConstraints c = new GridBagConstraints();
    setLayout(gridbag);
    int y = 0;
    c.gridx = 0;
    c.gridy = y++;
    c.gridwidth = 1;
    c.fill = GridBagConstraints.BOTH;
    c.anchor = GridBagConstraints.CENTER;
    int margin = 32;
    if (IJ.isMacOSX()) margin = 20;
    c.insets = new Insets(10, margin, 10, margin);
    choice = new Choice();
    for (int i = 0; i < modes.length; i++) choice.addItem(modes[i]);
    choice.select(0);
    choice.addItemListener(this);
    add(choice, c);

    CompositeImage ci = getImage();
    int nCheckBoxes = ci != null ? ci.getNChannels() : 3;
    if (nCheckBoxes > CompositeImage.MAX_CHANNELS) nCheckBoxes = CompositeImage.MAX_CHANNELS;
    checkbox = new Checkbox[nCheckBoxes];
    for (int i = 0; i < nCheckBoxes; i++) {
      checkbox[i] = new Checkbox("Channel " + (i + 1), true);
      c.insets = new Insets(0, 25, i < nCheckBoxes - 1 ? 0 : 10, 5);
      c.gridy = y++;
      add(checkbox[i], c);
      checkbox[i].addItemListener(this);
    }

    c.insets = new Insets(0, 15, 10, 15);
    c.fill = GridBagConstraints.NONE;
    c.gridy = y++;
    moreButton = new Button(moreLabel);
    moreButton.addActionListener(this);
    add(moreButton, c);
    update();

    pm = new PopupMenu();
    for (int i = 0; i < menuItems.length; i++) addPopupItem(menuItems[i]);
    add(pm);

    addKeyListener(IJ.getInstance()); // ImageJ handles keyboard shortcuts
    setResizable(false);
    pack();
    if (location == null) {
      GUI.center(this);
      location = getLocation();
    } else setLocation(location);
    show();
  }
コード例 #6
0
  public void run(String arg) {
    ImageWindow iw = WindowManager.getCurrentWindow();
    pw = jutils.getPW4SelCopy(iw);
    String title = pw.getTitle();
    float[][] yvals = pw.getYValues();
    float[][] xvals = pw.getXValues();
    int length = yvals[0].length;
    if (pw.getShowErrors()) errs = pw.getErrors(0, false);
    int[] colors = pw.getColors();
    colors[0] = 0;
    ScriptEngineManager manager = new ScriptEngineManager();
    engine = manager.getEngineByName("js");
    ce = (Compilable) engine;
    // hitcounter=0;

    c2 = 0.0f;
    iterations = 0;
    checkc2 = false;

    double[] stats = new double[3];
    tempx = new float[length];
    tempdata = new float[length];
    System.arraycopy(xvals[0], 0, tempx, 0, length);
    System.arraycopy(yvals[0], 0, tempdata, 0, length);
    pw.addPoints(tempx, new float[tempx.length], false);
    series = pw.getNpts().length - 1;
    double[] params = new double[10];
    int[] fixes = {0, 0, 0, 1, 1, 1, 1, 1, 1, 1};
    init_options(params, fixes);
    if (!init_functions()) {
      return;
    }

    while (showoptions(params, fixes)) {
      NLLSfit_v2 fitclass;
      if (checkc2) {
        fitclass = new NLLSfit_v2(this, 0);
      } else {
        fitclass = new NLLSfit_v2(this, 0.0001, 50, 0.1);
      }
      float[] fit = fitclass.fitdata(params, fixes, constraints, yvals[0], weights, stats, true);
      pw.updateSeries(fit, series, false);
      c2 = (float) stats[1];
      iterations = (int) stats[0];
    }

    IJ.log("Chi Squared = " + (float) stats[1]);
    IJ.log("Iterations = " + (int) stats[0]);
    for (int i = 0; i < 10; i++) {
      IJ.log("P" + (i + 1) + " = " + (float) params[i] + " fixed = " + fixes[i]);
    }
    IJ.log("AIC = " + (float) stats[2]);
    // IJ.log("hits = "+hitcounter);
    set_options(params, fixes);
  }
コード例 #7
0
  private boolean showDialog() {
    String[] types = {"RAW", "JPEG", "ZLIB"};
    GenericDialog gd = new GenericDialog("Generate Bricks");
    gd.addChoice("FileType", types, filetype);
    gd.addNumericField("JPEG quality", jpeg_quality, 0);
    gd.addNumericField("Max file size (MB)", bdsizelimit, 0);

    int[] wlist = WindowManager.getIDList();
    if (wlist == null) return false;

    String[] titles = new String[wlist.length];
    for (int i = 0; i < wlist.length; i++) titles[i] = "";

    int tnum = 0;
    for (int i = 0; i < wlist.length; i++) {
      ImagePlus imp = WindowManager.getImage(wlist[i]);
      if (imp != null) {
        titles[tnum] = imp.getTitle();
        tnum++;
      }
    }
    gd.addChoice("Source image: ", titles, titles[0]);

    gd.showDialog();
    if (gd.wasCanceled()) return false;

    filetype = types[gd.getNextChoiceIndex()];
    jpeg_quality = (int) gd.getNextNumber();
    if (jpeg_quality > 100) jpeg_quality = 100;
    if (jpeg_quality < 0) jpeg_quality = 0;
    bdsizelimit = (int) gd.getNextNumber();

    int id = gd.getNextChoiceIndex();
    lvImgTitle = new ArrayList<String>();
    lvImgTitle.add(titles[id]);

    Prefs.set("filetype.string", filetype);
    Prefs.set("jpeg_quality.int", jpeg_quality);
    Prefs.set("bdsizelimit.int", bdsizelimit);

    return true;
  }
コード例 #8
0
 private boolean checkImage() {
   imp = WindowManager.getCurrentImage();
   if (imp == null) {
     IJ.beep();
     IJ.showStatus("No image");
     return false;
   }
   ip = setup(imp);
   if (ip == null) return false;
   return true;
 }
コード例 #9
0
ファイル: ImageJ.java プロジェクト: Jondeen/imagej1
 void saveWindowLocations() {
   Frame frame = WindowManager.getFrame("B&C");
   if (frame != null) Prefs.saveLocation(ContrastAdjuster.LOC_KEY, frame.getLocation());
   frame = WindowManager.getFrame("Threshold");
   if (frame != null) Prefs.saveLocation(ThresholdAdjuster.LOC_KEY, frame.getLocation());
   frame = WindowManager.getFrame("Results");
   if (frame != null) {
     Prefs.saveLocation(TextWindow.LOC_KEY, frame.getLocation());
     Dimension d = frame.getSize();
     Prefs.set(TextWindow.WIDTH_KEY, d.width);
     Prefs.set(TextWindow.HEIGHT_KEY, d.height);
   }
   frame = WindowManager.getFrame("Log");
   if (frame != null) {
     Prefs.saveLocation(TextWindow.LOG_LOC_KEY, frame.getLocation());
     Dimension d = frame.getSize();
     Prefs.set(TextWindow.LOG_WIDTH_KEY, d.width);
     Prefs.set(TextWindow.LOG_HEIGHT_KEY, d.height);
   }
 }
コード例 #10
0
ファイル: ImageJ.java プロジェクト: chrisp87/ImageJA
 private boolean ignoreArrowKeys(ImagePlus imp) {
   Frame frame = WindowManager.getFrontWindow();
   String title = frame.getTitle();
   if (title != null && title.equals("ROI Manager")) return true;
   // Control Panel?
   if (frame != null && frame instanceof javax.swing.JFrame) return true;
   ImageWindow win = imp.getWindow();
   // LOCI Data Browser window?
   if (imp.getStackSize() > 1 && win != null && win.getClass().getName().startsWith("loci"))
     return true;
   return false;
 }
コード例 #11
0
 public void run(String arg) {
   GenericDialog gd = new GenericDialog("Options");
   gd.addCheckbox("Add_Titles", true);
   gd.addCheckbox("Close Original", false);
   gd.showDialog();
   if (gd.wasCanceled()) {
     return;
   }
   boolean addtitles = gd.getNextBoolean();
   boolean closeorig = gd.getNextBoolean();
   // first get the table window
   Frame[] niframes = WindowManager.getNonImageWindows();
   boolean first = true;
   TextWindow tw2 = null;
   int ncols = 0;
   String[] col_labels = null;
   for (int i = 0; i < niframes.length; i++) {
     if (niframes[i] instanceof TextWindow && !niframes[i].getTitle().equals("Log")) {
       TextWindow tw = (TextWindow) niframes[i];
       TextPanel tp = tw.getTextPanel();
       List<List<String>> listtable = table_tools.table2listtable(tp);
       if (listtable.size() == 0) {
         col_labels = table_tools.getcollabels(tp);
         ncols = col_labels.length;
         ArrayList<String> temp = new ArrayList<String>();
         for (int j = 0; j < ncols; j++) temp.add("");
         listtable.add(temp);
       }
       if (first) {
         col_labels = table_tools.getcollabels(tp);
         ncols = col_labels.length;
         String headings = tp.getColumnHeadings();
         if (addtitles) {
           String[] titles = repeated(tw.getTitle(), listtable.size());
           table_tools.add_listtable_column(listtable, titles, 0);
           headings = "name\t" + headings;
         }
         tw2 =
             new TextWindow(
                 "Combined Table", headings, table_tools.print_listtable(listtable), 400, 200);
         first = false;
       } else {
         if (addtitles) {
           String[] titles = repeated(tw.getTitle(), listtable.size());
           table_tools.add_listtable_column(listtable, titles, 0);
         }
         tw2.append(table_tools.print_listtable(listtable));
       }
       if (closeorig) tw.close();
     }
   }
 }
コード例 #12
0
ファイル: ImageJ.java プロジェクト: chrisp87/ImageJA
 void saveWindowLocations() {
   Window win = WindowManager.getWindow("B&C");
   if (win != null) Prefs.saveLocation(ContrastAdjuster.LOC_KEY, win.getLocation());
   win = WindowManager.getWindow("Threshold");
   if (win != null) Prefs.saveLocation(ThresholdAdjuster.LOC_KEY, win.getLocation());
   win = WindowManager.getWindow("Results");
   if (win != null) {
     Prefs.saveLocation(TextWindow.LOC_KEY, win.getLocation());
     Dimension d = win.getSize();
     Prefs.set(TextWindow.WIDTH_KEY, d.width);
     Prefs.set(TextWindow.HEIGHT_KEY, d.height);
   }
   win = WindowManager.getWindow("Log");
   if (win != null) {
     Prefs.saveLocation(TextWindow.LOG_LOC_KEY, win.getLocation());
     Dimension d = win.getSize();
     Prefs.set(TextWindow.LOG_WIDTH_KEY, d.width);
     Prefs.set(TextWindow.LOG_HEIGHT_KEY, d.height);
   }
   win = WindowManager.getWindow("ROI Manager");
   if (win != null) Prefs.saveLocation(RoiManager.LOC_KEY, win.getLocation());
 }
コード例 #13
0
  public void run(String arg) {
    ImagePlus imp = WindowManager.getCurrentImage();
    if (!(imp instanceof Image5D)) {
      IJ.error("Current Image is not an Image5D.");
      return;
    }
    IJ.register(Add_Empty_Slice.class);

    Image5D i5d = (Image5D) imp;
    Image5DWindow win = ((Image5DWindow) i5d.getWindow());
    int n = i5d.getNSlices();

    i5d.expandDimension(3, n + 1, true);

    win.updateSliceSelector();
  }
コード例 #14
0
 public void run(String arg) {
   ImagePlus imp = WindowManager.getCurrentImage();
   if (imp == null) {
     IJ.noImage();
     return;
   }
   if (imp.getStackSize() > 1) {
     IJ.error("This command requires a montage");
     return;
   }
   GenericDialog gd = new GenericDialog("Stack Maker");
   gd.addNumericField("Images_per_row: ", w, 0);
   gd.addNumericField("Images_per_column: ", h, 0);
   gd.addNumericField("Border width: ", b, 0);
   gd.showDialog();
   if (gd.wasCanceled()) return;
   w = (int) gd.getNextNumber();
   h = (int) gd.getNextNumber();
   b = (int) gd.getNextNumber();
   ImageStack stack = makeStack(imp.getProcessor(), w, h, b);
   new ImagePlus("Stack", stack).show();
 }
コード例 #15
0
ファイル: ImageJ.java プロジェクト: chrisp87/ImageJA
  public void keyPressed(KeyEvent e) {
    // if (e.isConsumed()) return;
    int keyCode = e.getKeyCode();
    IJ.setKeyDown(keyCode);
    hotkey = false;
    if (keyCode == KeyEvent.VK_CONTROL || keyCode == KeyEvent.VK_SHIFT) return;
    char keyChar = e.getKeyChar();
    int flags = e.getModifiers();
    if (IJ.debugMode)
      IJ.log(
          "keyPressed: code="
              + keyCode
              + " ("
              + KeyEvent.getKeyText(keyCode)
              + "), char=\""
              + keyChar
              + "\" ("
              + (int) keyChar
              + "), flags="
              + KeyEvent.getKeyModifiersText(flags));
    boolean shift = (flags & KeyEvent.SHIFT_MASK) != 0;
    boolean control = (flags & KeyEvent.CTRL_MASK) != 0;
    boolean alt = (flags & KeyEvent.ALT_MASK) != 0;
    boolean meta = (flags & KeyEvent.META_MASK) != 0;
    String cmd = null;
    ImagePlus imp = WindowManager.getCurrentImage();
    boolean isStack = (imp != null) && (imp.getStackSize() > 1);

    if (imp != null
        && !control
        && ((keyChar >= 32 && keyChar <= 255) || keyChar == '\b' || keyChar == '\n')) {
      Roi roi = imp.getRoi();
      if (roi instanceof TextRoi) {
        if ((flags & KeyEvent.META_MASK) != 0 && IJ.isMacOSX()) return;
        if (alt) {
          switch (keyChar) {
            case 'u':
            case 'm':
              keyChar = IJ.micronSymbol;
              break;
            case 'A':
              keyChar = IJ.angstromSymbol;
              break;
            default:
          }
        }
        ((TextRoi) roi).addChar(keyChar);
        return;
      }
    }

    // Handle one character macro shortcuts
    if (!control && !meta) {
      Hashtable macroShortcuts = Menus.getMacroShortcuts();
      if (macroShortcuts.size() > 0) {
        if (shift) cmd = (String) macroShortcuts.get(new Integer(keyCode + 200));
        else cmd = (String) macroShortcuts.get(new Integer(keyCode));
        if (cmd != null) {
          // MacroInstaller.runMacroCommand(cmd);
          commandName = cmd;
          MacroInstaller.runMacroShortcut(cmd);
          return;
        }
      }
    }

    if ((!Prefs.requireControlKey || control || meta) && keyChar != '+') {
      Hashtable shortcuts = Menus.getShortcuts();
      if (shift) cmd = (String) shortcuts.get(new Integer(keyCode + 200));
      else cmd = (String) shortcuts.get(new Integer(keyCode));
    }

    if (cmd == null) {
      switch (keyChar) {
        case '<':
        case ',':
          if (isStack) cmd = "Previous Slice [<]";
          break;
        case '>':
        case '.':
        case ';':
          if (isStack) cmd = "Next Slice [>]";
          break;
        case '+':
        case '=':
          cmd = "In [+]";
          break;
        case '-':
          cmd = "Out [-]";
          break;
        case '/':
          cmd = "Reslice [/]...";
          break;
        default:
      }
    }

    if (cmd == null) {
      switch (keyCode) {
        case KeyEvent.VK_TAB:
          WindowManager.putBehind();
          return;
        case KeyEvent.VK_BACK_SPACE: // delete
          if (deleteOverlayRoi(imp)) return;
          cmd = "Clear";
          hotkey = true;
          break;
          // case KeyEvent.VK_BACK_SLASH: cmd=IJ.altKeyDown()?"Animation Options...":"Start
          // Animation"; break;
        case KeyEvent.VK_EQUALS:
          cmd = "In [+]";
          break;
        case KeyEvent.VK_MINUS:
          cmd = "Out [-]";
          break;
        case KeyEvent.VK_SLASH:
        case 0xbf:
          cmd = "Reslice [/]...";
          break;
        case KeyEvent.VK_COMMA:
        case 0xbc:
          if (isStack) cmd = "Previous Slice [<]";
          break;
        case KeyEvent.VK_PERIOD:
        case 0xbe:
          if (isStack) cmd = "Next Slice [>]";
          break;
        case KeyEvent.VK_LEFT:
        case KeyEvent.VK_RIGHT:
        case KeyEvent.VK_UP:
        case KeyEvent.VK_DOWN: // arrow keys
          if (imp == null) return;
          Roi roi = imp.getRoi();
          if (IJ.shiftKeyDown() && imp == Orthogonal_Views.getImage()) return;
          boolean stackKey = imp.getStackSize() > 1 && (roi == null || IJ.shiftKeyDown());
          boolean zoomKey = roi == null || IJ.shiftKeyDown() || IJ.controlKeyDown();
          if (stackKey && keyCode == KeyEvent.VK_RIGHT) cmd = "Next Slice [>]";
          else if (stackKey && keyCode == KeyEvent.VK_LEFT) cmd = "Previous Slice [<]";
          else if (zoomKey
              && keyCode == KeyEvent.VK_DOWN
              && !ignoreArrowKeys(imp)
              && Toolbar.getToolId() < Toolbar.SPARE6) cmd = "Out [-]";
          else if (zoomKey
              && keyCode == KeyEvent.VK_UP
              && !ignoreArrowKeys(imp)
              && Toolbar.getToolId() < Toolbar.SPARE6) cmd = "In [+]";
          else if (roi != null) {
            if ((flags & KeyEvent.ALT_MASK) != 0) roi.nudgeCorner(keyCode);
            else roi.nudge(keyCode);
            return;
          }
          break;
        case KeyEvent.VK_ESCAPE:
          abortPluginOrMacro(imp);
          return;
        case KeyEvent.VK_ENTER:
          WindowManager.toFront(this);
          return;
        default:
          break;
      }
    }

    if (cmd != null && !cmd.equals("")) {
      commandName = cmd;
      if (cmd.equals("Fill") || cmd.equals("Draw")) hotkey = true;
      if (cmd.charAt(0) == MacroInstaller.commandPrefix) MacroInstaller.runMacroShortcut(cmd);
      else {
        doCommand(cmd);
        keyPressedTime = System.currentTimeMillis();
        lastKeyCommand = cmd;
      }
    }
  }
コード例 #16
0
 public void windowActivated(WindowEvent e) {
   ImageJ ij = IJ.getInstance();
   if (IJ.isMacOSX() && ij != null && !ij.isActive() && !(this instanceof ThresholdAdjuster))
     ij.toFront();
   WindowManager.setWindow(this);
 }
コード例 #17
0
ファイル: Channels.java プロジェクト: hellotod/HadoopLung
 CompositeImage getImage() {
   ImagePlus imp = WindowManager.getCurrentImage();
   if (imp == null || !imp.isComposite()) return null;
   else return (CompositeImage) imp;
 }
コード例 #18
0
ファイル: ImageJ.java プロジェクト: chrisp87/ImageJA
 public void mousePressed(MouseEvent e) {
   Undo.reset();
   if (!Prefs.noClickToGC) System.gc();
   IJ.showStatus(version() + IJ.freeMemory());
   if (IJ.debugMode) IJ.log("Windows: " + WindowManager.getWindowCount());
 }
コード例 #19
0
  public void run(String arg) {
    ImagePlus imp = WindowManager.getCurrentImage();
    Calibration cal = imp.getCalibration();
    GenericDialog gd = new GenericDialog("Options");
    int subsize = 32;
    gd.addNumericField("Subregion Size (pixels)?", subsize, 0);
    int stepsize = 16;
    gd.addNumericField("Step Size?", stepsize, 0);
    int shift = 3;
    gd.addNumericField("STICS temporal Shift?", shift, 0);
    float xoffset = 0.0f;
    gd.addNumericField("X_Offset", xoffset, 5, 15, null);
    float yoffset = 0.0f;
    gd.addNumericField("Y_Offset", yoffset, 5, 15, null);
    float multiplier = 8.0f;
    gd.addNumericField("Velocity Multiplier", multiplier, 5, 15, null);
    float ftime = 1.0f;
    gd.addNumericField("Frame_Time(min)", ftime, 5, 15, null);
    float scaling = (float) cal.pixelWidth;
    gd.addNumericField("Pixel_Size(um)", scaling, 5, 15, null);
    boolean norm = true;
    gd.addCheckbox("Normalize_Vector_lengths?", norm);
    boolean centered = true;
    gd.addCheckbox("Center_Vectors?", centered);
    float magthresh = 0.0f;
    gd.addNumericField("Magnitude_Threshhold?", magthresh, 5, 15, null);
    int rlength = 10;
    gd.addNumericField("Running_avg_length", rlength, 0);
    int inc = 5;
    gd.addNumericField("Start_frame_increment", inc, 0);
    gd.showDialog();
    if (gd.wasCanceled()) {
      return;
    }
    subsize = (int) gd.getNextNumber();
    stepsize = (int) gd.getNextNumber();
    shift = (int) gd.getNextNumber();
    xoffset = (float) gd.getNextNumber();
    yoffset = (float) gd.getNextNumber();
    multiplier = (float) gd.getNextNumber();
    ftime = (float) gd.getNextNumber();
    scaling = (float) gd.getNextNumber();
    norm = gd.getNextBoolean();
    centered = gd.getNextBoolean();
    magthresh = (float) gd.getNextNumber();
    rlength = (int) gd.getNextNumber();
    inc = (int) gd.getNextNumber();

    int width = imp.getWidth();
    int xregions = 1 + (int) (((float) width - (float) subsize) / (float) stepsize);
    int newwidth = xregions * subsize;
    int height = imp.getHeight();
    int yregions = 1 + (int) (((float) height - (float) subsize) / (float) stepsize);
    int newheight = yregions * subsize;
    ImageStack stack = imp.getStack();
    int slices = imp.getNSlices();
    int channels = imp.getNChannels();
    int frames = imp.getNFrames();
    if (frames == 1) {
      frames = slices;
      slices = 1;
    }

    Roi roi = imp.getRoi();
    if (roi == null) {
      roi = new Roi(0, 0, width, height);
    }

    STICS_map map = new STICS_map(subsize, stepsize);
    Object[] tseries = jutils.get3DTSeries(stack, 0, 0, frames, slices, channels);
    map.update_STICS_map(tseries, width, height, 0, rlength, roi.getPolygon(), shift);
    FloatProcessor fp =
        map.get_map(scaling, ftime, stepsize, centered, norm, multiplier, stepsize, magthresh);
    ImageStack vector_stack = new ImageStack(fp.getWidth(), fp.getHeight());
    vector_stack.addSlice("", fp);
    float[][] vel = map.get_scaled_velocities(scaling, ftime, stepsize);
    ImageStack velstack = new ImageStack(map.xregions, map.yregions);
    velstack.addSlice("", vel[0]);
    velstack.addSlice("", vel[1]);
    int velframes = 2;
    IJ.showStatus("frame " + 0 + " calculated");
    for (int i = inc; i < (frames - rlength); i += inc) {
      map.update_STICS_map(tseries, width, height, i, rlength, roi.getPolygon(), shift);
      FloatProcessor fp2 =
          map.get_map(scaling, ftime, stepsize, centered, norm, multiplier, stepsize, magthresh);
      vector_stack.addSlice("", fp2);
      vel = map.get_scaled_velocities(scaling, ftime, stepsize);
      velstack.addSlice("", vel[0]);
      velstack.addSlice("", vel[1]);
      velframes += 2;
      IJ.showStatus("frame " + i + " calculated");
    }
    (new ImagePlus("STICS Vectors", vector_stack)).show();
    ImagePlus imp3 = new ImagePlus("Velocities", velstack);
    imp3.setOpenAsHyperStack(true);
    imp3.setDimensions(2, 1, velframes / 2);
    new CompositeImage(imp3, CompositeImage.COLOR).show();
  }
コード例 #20
0
ファイル: Channels.java プロジェクト: hellotod/HadoopLung
 public void itemStateChanged(ItemEvent e) {
   ImagePlus imp = WindowManager.getCurrentImage();
   if (imp == null) return;
   if (!imp.isComposite()) {
     int channels = imp.getNChannels();
     if (channels == 1 && imp.getStackSize() <= 4) channels = imp.getStackSize();
     if (imp.getBitDepth() == 24 || (channels > 1 && channels < CompositeImage.MAX_CHANNELS)) {
       GenericDialog gd = new GenericDialog(imp.getTitle());
       gd.addMessage("Convert to multi-channel composite image?");
       gd.showDialog();
       if (gd.wasCanceled()) return;
       else IJ.doCommand("Make Composite");
     } else {
       IJ.error(
           "Channels",
           "A composite image is required (e.g., "
               + moreLabel
               + " Open HeLa Cells),\nor create one using "
               + moreLabel
               + " Make Composite.");
       return;
     }
   }
   if (!imp.isComposite()) return;
   CompositeImage ci = (CompositeImage) imp;
   Object source = e.getSource();
   if (source == choice) {
     int index = ((Choice) source).getSelectedIndex();
     switch (index) {
       case 0:
         ci.setMode(IJ.COMPOSITE);
         break;
       case 1:
         ci.setMode(IJ.COLOR);
         break;
       case 2:
         ci.setMode(IJ.GRAYSCALE);
         break;
     }
     ci.updateAndDraw();
     if (Recorder.record) {
       String mode = null;
       switch (index) {
         case 0:
           mode = "composite";
           break;
         case 1:
           mode = "color";
           break;
         case 2:
           mode = "grayscale";
           break;
       }
       Recorder.record("Stack.setDisplayMode", mode);
     }
   } else if (source instanceof Checkbox) {
     for (int i = 0; i < checkbox.length; i++) {
       Checkbox cb = (Checkbox) source;
       if (cb == checkbox[i]) {
         if (ci.getMode() == IJ.COMPOSITE) {
           boolean[] active = ci.getActiveChannels();
           active[i] = cb.getState();
           if (Recorder.record) {
             String str = "";
             for (int c = 0; c < ci.getNChannels(); c++) str += active[c] ? "1" : "0";
             Recorder.record("Stack.setActiveChannels", str);
             Recorder.record("//Stack.toggleChannel", imp.getChannel());
           }
         } else {
           imp.setPosition(i + 1, imp.getSlice(), imp.getFrame());
           if (Recorder.record) Recorder.record("Stack.setChannel", i + 1);
         }
         ci.updateAndDraw();
         return;
       }
     }
   }
 }
コード例 #21
0
  public void build_bricks() {

    ImagePlus imp;
    ImagePlus orgimp;
    ImageStack stack;
    FileInfo finfo;

    if (lvImgTitle.isEmpty()) return;
    orgimp = WindowManager.getImage(lvImgTitle.get(0));
    imp = orgimp;

    finfo = imp.getFileInfo();
    if (finfo == null) return;

    int[] dims = imp.getDimensions();
    int imageW = dims[0];
    int imageH = dims[1];
    int nCh = dims[2];
    int imageD = dims[3];
    int nFrame = dims[4];
    int bdepth = imp.getBitDepth();
    double xspc = finfo.pixelWidth;
    double yspc = finfo.pixelHeight;
    double zspc = finfo.pixelDepth;
    double z_aspect = Math.max(xspc, yspc) / zspc;

    int orgW = imageW;
    int orgH = imageH;
    int orgD = imageD;
    double orgxspc = xspc;
    double orgyspc = yspc;
    double orgzspc = zspc;

    lv = lvImgTitle.size();
    if (filetype == "JPEG") {
      for (int l = 0; l < lv; l++) {
        if (WindowManager.getImage(lvImgTitle.get(l)).getBitDepth() != 8) {
          IJ.error("A SOURCE IMAGE MUST BE 8BIT GLAYSCALE");
          return;
        }
      }
    }

    // calculate levels
    /*		int baseXY = 256;
    		int baseZ = 256;

    		if (z_aspect < 0.5) baseZ = 128;
    		if (z_aspect > 2.0) baseXY = 128;
    		if (z_aspect >= 0.5 && z_aspect < 1.0) baseZ = (int)(baseZ*z_aspect);
    		if (z_aspect > 1.0 && z_aspect <= 2.0) baseXY = (int)(baseXY/z_aspect);

    		IJ.log("Z_aspect: " + z_aspect);
    		IJ.log("BaseXY: " + baseXY);
    		IJ.log("BaseZ: " + baseZ);
    */

    int baseXY = 256;
    int baseZ = 128;
    int dbXY = Math.max(orgW, orgH) / baseXY;
    if (Math.max(orgW, orgH) % baseXY > 0) dbXY *= 2;
    int dbZ = orgD / baseZ;
    if (orgD % baseZ > 0) dbZ *= 2;
    lv = Math.max(log2(dbXY), log2(dbZ)) + 1;

    int ww = orgW;
    int hh = orgH;
    int dd = orgD;
    for (int l = 0; l < lv; l++) {
      int bwnum = ww / baseXY;
      if (ww % baseXY > 0) bwnum++;
      int bhnum = hh / baseXY;
      if (hh % baseXY > 0) bhnum++;
      int bdnum = dd / baseZ;
      if (dd % baseZ > 0) bdnum++;

      if (bwnum % 2 == 0) bwnum++;
      if (bhnum % 2 == 0) bhnum++;
      if (bdnum % 2 == 0) bdnum++;

      int bw = (bwnum <= 1) ? ww : ww / bwnum + 1 + (ww % bwnum > 0 ? 1 : 0);
      int bh = (bhnum <= 1) ? hh : hh / bhnum + 1 + (hh % bhnum > 0 ? 1 : 0);
      int bd = (bdnum <= 1) ? dd : dd / bdnum + 1 + (dd % bdnum > 0 ? 1 : 0);

      bwlist.add(bw);
      bhlist.add(bh);
      bdlist.add(bd);

      IJ.log("LEVEL: " + l);
      IJ.log("  width: " + ww);
      IJ.log("  hight: " + hh);
      IJ.log("  depth: " + dd);
      IJ.log("  bw: " + bw);
      IJ.log("  bh: " + bh);
      IJ.log("  bd: " + bd);

      int xyl2 = Math.max(ww, hh) / baseXY;
      if (Math.max(ww, hh) % baseXY > 0) xyl2 *= 2;
      if (lv - 1 - log2(xyl2) <= l) {
        ww /= 2;
        hh /= 2;
      }
      IJ.log("  xyl2: " + (lv - 1 - log2(xyl2)));

      int zl2 = dd / baseZ;
      if (dd % baseZ > 0) zl2 *= 2;
      if (lv - 1 - log2(zl2) <= l) dd /= 2;
      IJ.log("  zl2: " + (lv - 1 - log2(zl2)));

      if (l < lv - 1) {
        lvImgTitle.add(lvImgTitle.get(0) + "_level" + (l + 1));
        IJ.selectWindow(lvImgTitle.get(0));
        IJ.run(
            "Scale...",
            "x=- y=- z=- width="
                + ww
                + " height="
                + hh
                + " depth="
                + dd
                + " interpolation=Bicubic average process create title="
                + lvImgTitle.get(l + 1));
      }
    }

    for (int l = 0; l < lv; l++) {
      IJ.log(lvImgTitle.get(l));
    }

    Document doc = newXMLDocument();
    Element root = doc.createElement("BRK");
    root.setAttribute("version", "1.0");
    root.setAttribute("nLevel", String.valueOf(lv));
    root.setAttribute("nChannel", String.valueOf(nCh));
    root.setAttribute("nFrame", String.valueOf(nFrame));
    doc.appendChild(root);

    for (int l = 0; l < lv; l++) {
      IJ.showProgress(0.0);

      int[] dims2 = imp.getDimensions();
      IJ.log(
          "W: "
              + String.valueOf(dims2[0])
              + " H: "
              + String.valueOf(dims2[1])
              + " C: "
              + String.valueOf(dims2[2])
              + " D: "
              + String.valueOf(dims2[3])
              + " T: "
              + String.valueOf(dims2[4])
              + " b: "
              + String.valueOf(bdepth));

      bw = bwlist.get(l).intValue();
      bh = bhlist.get(l).intValue();
      bd = bdlist.get(l).intValue();

      boolean force_pow2 = false;
      /*			if(IsPowerOf2(bw) && IsPowerOf2(bh) && IsPowerOf2(bd)) force_pow2 = true;

      			if(force_pow2){
      				//force pow2
      				if(Pow2(bw) > bw) bw = Pow2(bw)/2;
      				if(Pow2(bh) > bh) bh = Pow2(bh)/2;
      				if(Pow2(bd) > bd) bd = Pow2(bd)/2;
      			}

      			if(bw > imageW) bw = (Pow2(imageW) == imageW) ? imageW : Pow2(imageW)/2;
      			if(bh > imageH) bh = (Pow2(imageH) == imageH) ? imageH : Pow2(imageH)/2;
      			if(bd > imageD) bd = (Pow2(imageD) == imageD) ? imageD : Pow2(imageD)/2;

      */
      if (bw > imageW) bw = imageW;
      if (bh > imageH) bh = imageH;
      if (bd > imageD) bd = imageD;

      if (bw <= 1 || bh <= 1 || bd <= 1) break;

      if (filetype == "JPEG" && (bw < 8 || bh < 8)) break;

      Element lvnode = doc.createElement("Level");
      lvnode.setAttribute("lv", String.valueOf(l));
      lvnode.setAttribute("imageW", String.valueOf(imageW));
      lvnode.setAttribute("imageH", String.valueOf(imageH));
      lvnode.setAttribute("imageD", String.valueOf(imageD));
      lvnode.setAttribute("xspc", String.valueOf(xspc));
      lvnode.setAttribute("yspc", String.valueOf(yspc));
      lvnode.setAttribute("zspc", String.valueOf(zspc));
      lvnode.setAttribute("bitDepth", String.valueOf(bdepth));
      root.appendChild(lvnode);

      Element brksnode = doc.createElement("Bricks");
      brksnode.setAttribute("brick_baseW", String.valueOf(bw));
      brksnode.setAttribute("brick_baseH", String.valueOf(bh));
      brksnode.setAttribute("brick_baseD", String.valueOf(bd));
      lvnode.appendChild(brksnode);

      ArrayList<Brick> bricks = new ArrayList<Brick>();
      int mw, mh, md, mw2, mh2, md2;
      double tx0, ty0, tz0, tx1, ty1, tz1;
      double bx0, by0, bz0, bx1, by1, bz1;
      for (int k = 0; k < imageD; k += bd) {
        if (k > 0) k--;
        for (int j = 0; j < imageH; j += bh) {
          if (j > 0) j--;
          for (int i = 0; i < imageW; i += bw) {
            if (i > 0) i--;
            mw = Math.min(bw, imageW - i);
            mh = Math.min(bh, imageH - j);
            md = Math.min(bd, imageD - k);

            if (force_pow2) {
              mw2 = Pow2(mw);
              mh2 = Pow2(mh);
              md2 = Pow2(md);
            } else {
              mw2 = mw;
              mh2 = mh;
              md2 = md;
            }

            if (filetype == "JPEG") {
              if (mw2 < 8) mw2 = 8;
              if (mh2 < 8) mh2 = 8;
            }

            tx0 = i == 0 ? 0.0d : ((mw2 - mw + 0.5d) / mw2);
            ty0 = j == 0 ? 0.0d : ((mh2 - mh + 0.5d) / mh2);
            tz0 = k == 0 ? 0.0d : ((md2 - md + 0.5d) / md2);

            tx1 = 1.0d - 0.5d / mw2;
            if (mw < bw) tx1 = 1.0d;
            if (imageW - i == bw) tx1 = 1.0d;

            ty1 = 1.0d - 0.5d / mh2;
            if (mh < bh) ty1 = 1.0d;
            if (imageH - j == bh) ty1 = 1.0d;

            tz1 = 1.0d - 0.5d / md2;
            if (md < bd) tz1 = 1.0d;
            if (imageD - k == bd) tz1 = 1.0d;

            bx0 = i == 0 ? 0.0d : (i + 0.5d) / (double) imageW;
            by0 = j == 0 ? 0.0d : (j + 0.5d) / (double) imageH;
            bz0 = k == 0 ? 0.0d : (k + 0.5d) / (double) imageD;

            bx1 = Math.min((i + bw - 0.5d) / (double) imageW, 1.0d);
            if (imageW - i == bw) bx1 = 1.0d;

            by1 = Math.min((j + bh - 0.5d) / (double) imageH, 1.0d);
            if (imageH - j == bh) by1 = 1.0d;

            bz1 = Math.min((k + bd - 0.5d) / (double) imageD, 1.0d);
            if (imageD - k == bd) bz1 = 1.0d;

            int x, y, z;
            x = i - (mw2 - mw);
            y = j - (mh2 - mh);
            z = k - (md2 - md);
            bricks.add(
                new Brick(
                    x, y, z, mw2, mh2, md2, 0, 0, tx0, ty0, tz0, tx1, ty1, tz1, bx0, by0, bz0, bx1,
                    by1, bz1));
          }
        }
      }

      Element fsnode = doc.createElement("Files");
      lvnode.appendChild(fsnode);

      stack = imp.getStack();

      int totalbricknum = nFrame * nCh * bricks.size();
      int curbricknum = 0;
      for (int f = 0; f < nFrame; f++) {
        for (int ch = 0; ch < nCh; ch++) {
          int sizelimit = bdsizelimit * 1024 * 1024;
          int bytecount = 0;
          int filecount = 0;
          int pd_bufsize = Math.max(sizelimit, bw * bh * bd * bdepth / 8);
          byte[] packed_data = new byte[pd_bufsize];
          String base_dataname =
              basename
                  + "_Lv"
                  + String.valueOf(l)
                  + "_Ch"
                  + String.valueOf(ch)
                  + "_Fr"
                  + String.valueOf(f);
          String current_dataname = base_dataname + "_data" + filecount;

          Brick b_first = bricks.get(0);
          if (b_first.z_ != 0) IJ.log("warning");
          int st_z = b_first.z_;
          int ed_z = b_first.z_ + b_first.d_;
          LinkedList<ImageProcessor> iplist = new LinkedList<ImageProcessor>();
          for (int s = st_z; s < ed_z; s++)
            iplist.add(stack.getProcessor(imp.getStackIndex(ch + 1, s + 1, f + 1)));

          //					ImagePlus test;
          //					ImageStack tsst;
          //					test = NewImage.createByteImage("test", imageW, imageH, imageD,
          // NewImage.FILL_BLACK);
          //					tsst = test.getStack();
          for (int i = 0; i < bricks.size(); i++) {
            Brick b = bricks.get(i);

            if (ed_z > b.z_ || st_z < b.z_ + b.d_) {
              if (b.z_ > st_z) {
                for (int s = 0; s < b.z_ - st_z; s++) iplist.pollFirst();
                st_z = b.z_;
              } else if (b.z_ < st_z) {
                IJ.log("warning");
                for (int s = st_z - 1; s > b.z_; s--)
                  iplist.addFirst(stack.getProcessor(imp.getStackIndex(ch + 1, s + 1, f + 1)));
                st_z = b.z_;
              }

              if (b.z_ + b.d_ > ed_z) {
                for (int s = ed_z; s < b.z_ + b.d_; s++)
                  iplist.add(stack.getProcessor(imp.getStackIndex(ch + 1, s + 1, f + 1)));
                ed_z = b.z_ + b.d_;
              } else if (b.z_ + b.d_ < ed_z) {
                IJ.log("warning");
                for (int s = 0; s < ed_z - (b.z_ + b.d_); s++) iplist.pollLast();
                ed_z = b.z_ + b.d_;
              }
            } else {
              IJ.log("warning");
              iplist.clear();
              st_z = b.z_;
              ed_z = b.z_ + b.d_;
              for (int s = st_z; s < ed_z; s++)
                iplist.add(stack.getProcessor(imp.getStackIndex(ch + 1, s + 1, f + 1)));
            }

            if (iplist.size() != b.d_) {
              IJ.log("Stack Error");
              return;
            }

            //						int zz = st_z;

            int bsize = 0;
            byte[] bdata = new byte[b.w_ * b.h_ * b.d_ * bdepth / 8];
            Iterator<ImageProcessor> ipite = iplist.iterator();
            while (ipite.hasNext()) {

              //							ImageProcessor tsip = tsst.getProcessor(zz+1);

              ImageProcessor ip = ipite.next();
              ip.setRoi(b.x_, b.y_, b.w_, b.h_);
              if (bdepth == 8) {
                byte[] data = (byte[]) ip.crop().getPixels();
                System.arraycopy(data, 0, bdata, bsize, data.length);
                bsize += data.length;
              } else if (bdepth == 16) {
                ByteBuffer buffer = ByteBuffer.allocate(b.w_ * b.h_ * bdepth / 8);
                buffer.order(ByteOrder.LITTLE_ENDIAN);
                short[] data = (short[]) ip.crop().getPixels();
                for (short e : data) buffer.putShort(e);
                System.arraycopy(buffer.array(), 0, bdata, bsize, buffer.array().length);
                bsize += buffer.array().length;
              } else if (bdepth == 32) {
                ByteBuffer buffer = ByteBuffer.allocate(b.w_ * b.h_ * bdepth / 8);
                buffer.order(ByteOrder.LITTLE_ENDIAN);
                float[] data = (float[]) ip.crop().getPixels();
                for (float e : data) buffer.putFloat(e);
                System.arraycopy(buffer.array(), 0, bdata, bsize, buffer.array().length);
                bsize += buffer.array().length;
              }
            }

            String filename =
                basename
                    + "_Lv"
                    + String.valueOf(l)
                    + "_Ch"
                    + String.valueOf(ch)
                    + "_Fr"
                    + String.valueOf(f)
                    + "_ID"
                    + String.valueOf(i);

            int offset = bytecount;
            int datasize = bdata.length;

            if (filetype == "RAW") {
              int dummy = -1;
              // do nothing
            }
            if (filetype == "JPEG" && bdepth == 8) {
              try {
                DataBufferByte db = new DataBufferByte(bdata, datasize);
                Raster raster = Raster.createPackedRaster(db, b.w_, b.h_ * b.d_, 8, null);
                BufferedImage img =
                    new BufferedImage(b.w_, b.h_ * b.d_, BufferedImage.TYPE_BYTE_GRAY);
                img.setData(raster);
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                ImageOutputStream ios = ImageIO.createImageOutputStream(baos);
                String format = "jpg";
                Iterator<javax.imageio.ImageWriter> iter =
                    ImageIO.getImageWritersByFormatName("jpeg");
                javax.imageio.ImageWriter writer = iter.next();
                ImageWriteParam iwp = writer.getDefaultWriteParam();
                iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
                iwp.setCompressionQuality((float) jpeg_quality * 0.01f);
                writer.setOutput(ios);
                writer.write(null, new IIOImage(img, null, null), iwp);
                // ImageIO.write(img, format, baos);
                bdata = baos.toByteArray();
                datasize = bdata.length;
              } catch (IOException e) {
                e.printStackTrace();
                return;
              }
            }
            if (filetype == "ZLIB") {
              byte[] tmpdata = new byte[b.w_ * b.h_ * b.d_ * bdepth / 8];
              Deflater compresser = new Deflater();
              compresser.setInput(bdata);
              compresser.setLevel(Deflater.DEFAULT_COMPRESSION);
              compresser.setStrategy(Deflater.DEFAULT_STRATEGY);
              compresser.finish();
              datasize = compresser.deflate(tmpdata);
              bdata = tmpdata;
              compresser.end();
            }

            if (bytecount + datasize > sizelimit && bytecount > 0) {
              BufferedOutputStream fis = null;
              try {
                File file = new File(directory + current_dataname);
                fis = new BufferedOutputStream(new FileOutputStream(file));
                fis.write(packed_data, 0, bytecount);
              } catch (IOException e) {
                e.printStackTrace();
                return;
              } finally {
                try {
                  if (fis != null) fis.close();
                } catch (IOException e) {
                  e.printStackTrace();
                  return;
                }
              }
              filecount++;
              current_dataname = base_dataname + "_data" + filecount;
              bytecount = 0;
              offset = 0;
              System.arraycopy(bdata, 0, packed_data, bytecount, datasize);
              bytecount += datasize;
            } else {
              System.arraycopy(bdata, 0, packed_data, bytecount, datasize);
              bytecount += datasize;
            }

            Element filenode = doc.createElement("File");
            filenode.setAttribute("filename", current_dataname);
            filenode.setAttribute("channel", String.valueOf(ch));
            filenode.setAttribute("frame", String.valueOf(f));
            filenode.setAttribute("brickID", String.valueOf(i));
            filenode.setAttribute("offset", String.valueOf(offset));
            filenode.setAttribute("datasize", String.valueOf(datasize));
            filenode.setAttribute("filetype", String.valueOf(filetype));

            fsnode.appendChild(filenode);

            curbricknum++;
            IJ.showProgress((double) (curbricknum) / (double) (totalbricknum));
          }
          if (bytecount > 0) {
            BufferedOutputStream fis = null;
            try {
              File file = new File(directory + current_dataname);
              fis = new BufferedOutputStream(new FileOutputStream(file));
              fis.write(packed_data, 0, bytecount);
            } catch (IOException e) {
              e.printStackTrace();
              return;
            } finally {
              try {
                if (fis != null) fis.close();
              } catch (IOException e) {
                e.printStackTrace();
                return;
              }
            }
          }
        }
      }

      for (int i = 0; i < bricks.size(); i++) {
        Brick b = bricks.get(i);
        Element bricknode = doc.createElement("Brick");
        bricknode.setAttribute("id", String.valueOf(i));
        bricknode.setAttribute("st_x", String.valueOf(b.x_));
        bricknode.setAttribute("st_y", String.valueOf(b.y_));
        bricknode.setAttribute("st_z", String.valueOf(b.z_));
        bricknode.setAttribute("width", String.valueOf(b.w_));
        bricknode.setAttribute("height", String.valueOf(b.h_));
        bricknode.setAttribute("depth", String.valueOf(b.d_));
        brksnode.appendChild(bricknode);

        Element tboxnode = doc.createElement("tbox");
        tboxnode.setAttribute("x0", String.valueOf(b.tx0_));
        tboxnode.setAttribute("y0", String.valueOf(b.ty0_));
        tboxnode.setAttribute("z0", String.valueOf(b.tz0_));
        tboxnode.setAttribute("x1", String.valueOf(b.tx1_));
        tboxnode.setAttribute("y1", String.valueOf(b.ty1_));
        tboxnode.setAttribute("z1", String.valueOf(b.tz1_));
        bricknode.appendChild(tboxnode);

        Element bboxnode = doc.createElement("bbox");
        bboxnode.setAttribute("x0", String.valueOf(b.bx0_));
        bboxnode.setAttribute("y0", String.valueOf(b.by0_));
        bboxnode.setAttribute("z0", String.valueOf(b.bz0_));
        bboxnode.setAttribute("x1", String.valueOf(b.bx1_));
        bboxnode.setAttribute("y1", String.valueOf(b.by1_));
        bboxnode.setAttribute("z1", String.valueOf(b.bz1_));
        bricknode.appendChild(bboxnode);
      }

      if (l < lv - 1) {
        imp = WindowManager.getImage(lvImgTitle.get(l + 1));
        int[] newdims = imp.getDimensions();
        imageW = newdims[0];
        imageH = newdims[1];
        imageD = newdims[3];
        xspc = orgxspc * ((double) orgW / (double) imageW);
        yspc = orgyspc * ((double) orgH / (double) imageH);
        zspc = orgzspc * ((double) orgD / (double) imageD);
        bdepth = imp.getBitDepth();
      }
    }

    File newXMLfile = new File(directory + basename + ".vvd");
    writeXML(newXMLfile, doc);

    for (int l = 1; l < lv; l++) {
      imp = WindowManager.getImage(lvImgTitle.get(l));
      imp.changes = false;
      imp.close();
    }
  }
コード例 #22
0
  public boolean showDialog() {

    String bgChoice = "NoBg";
    int[] wList = WindowManager.getIDList();
    if (wList == null) {
      IJ.noImage();
      return false;
    }

    String[] sampleTitles = new String[wList.length];
    for (int i = 0; i < wList.length; i++) {
      ImagePlus imp = WindowManager.getImage(wList[i]);
      sampleTitles[i] = imp != null ? imp.getTitle() : "";
    }
    String[] bgTitles = new String[wList.length + 1];
    bgTitles[0] = "NoBg";
    for (int i = 1; i < wList.length + 1; i++) {
      bgTitles[i] = sampleTitles[i - 1];
    }
    for (int i = 1; i < (wList.length + 1); i++) {
      if (bgTitles[i] == bgStackTitle) bgChoice = bgStackTitle;
    }
    String sampleChoice = sampleTitles[0];
    for (int i = 1; i < (wList.length); i++) {
      if (sampleTitles[i] == sampleStackTitle) sampleChoice = sampleStackTitle;
    }

    String[] mirrors = new String[2];
    mirrors[0] = "No";
    mirrors[1] = "Yes";

    GenericDialog gd = new GenericDialog("PolScope 5Frame Calc");
    gd.addChoice("Sample:", sampleTitles, sampleChoice);
    gd.addChoice("Background:", bgTitles, bgChoice);
    gd.addChoice("Mirror:", mirrors, mirror);
    gd.addNumericField("Wavelength: ", wavelength, 1, 8, " nm");
    gd.addNumericField("Swing: ", swing, 3, 8, " wavelength");
    gd.addNumericField("Ret. Ceiling: ", retCeiling, 1, 8, " nm");
    gd.addNumericField("Orient. Ref.: ", azimRef, 1, 8, " degree");
    gd.showDialog();
    if (gd.wasCanceled()) return false;
    int index1 = gd.getNextChoiceIndex();
    int index2 = gd.getNextChoiceIndex();
    int index3 = gd.getNextChoiceIndex();
    wavelength = (float) gd.getNextNumber();
    swing = (float) gd.getNextNumber();
    retCeiling = (float) gd.getNextNumber();
    azimRef = (float) gd.getNextNumber();

    imp1 = WindowManager.getImage(wList[index1]);
    sampleStackTitle = sampleTitles[index1];
    bgStackTitle = bgTitles[index2];
    if (bgStackTitle == "NoBg") {
      imp2 =
          WindowManager.getImage(
              wList[
                  index1]); // only to assign a valid ImagePlus to imp2 which is not used when NoBg
    } else {
      imp2 = WindowManager.getImage(wList[index2 - 1]);
    }
    mirror = mirrors[index3];

    return true;
  }
コード例 #23
0
 public void run(String arg) {
   Frame[] niframes = WindowManager.getNonImageWindows();
   String[] titles = new String[niframes.length + 1];
   for (int i = 0; i < niframes.length; i++) {
     titles[i] = niframes[i].getTitle();
   }
   titles[niframes.length] = "Clipboard";
   GenericDialog gd = new GenericDialog("Windows");
   boolean importfile = false;
   gd.addCheckbox("Import from file?", importfile);
   gd.addChoice("Windows", titles, titles[0]);
   boolean hasxvals = false;
   gd.addCheckbox("X Vals Column?", hasxvals);
   boolean multix = false;
   gd.addCheckbox("Multi_X_Columns?", multix);
   boolean skipendzeros = false;
   gd.addCheckbox("Skip_end_zeros?", skipendzeros);
   String[] delimiters = {"Tab", "Comma", "Space"};
   gd.addChoice("Delimiter", delimiters, delimiters[0]);
   gd.showDialog();
   if (gd.wasCanceled()) {
     return;
   }
   importfile = gd.getNextBoolean();
   int index = gd.getNextChoiceIndex();
   hasxvals = gd.getNextBoolean();
   multix = gd.getNextBoolean();
   skipendzeros = gd.getNextBoolean();
   int delimindex = gd.getNextChoiceIndex();
   if (multix) hasxvals = true;
   String textdata = "";
   if (importfile) {
     OpenDialog od = new OpenDialog("Open File", "", ".txt");
     String directory = od.getDirectory();
     String name = od.getFileName();
     if (name == null) {
       return;
     }
     try {
       File infile = new File(directory + name);
       BufferedReader b = new BufferedReader(new FileReader(infile));
       textdata = (new jdataio()).readstringfile(b);
       b.close();
     } catch (IOException e) {
       return;
     }
   } else {
     if (index == niframes.length) {
       // here we get the data from the clipboard
       Transferable t = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null);
       try {
         if (t != null && t.isDataFlavorSupported(DataFlavor.stringFlavor)) {
           textdata = (String) t.getTransferData(DataFlavor.stringFlavor);
         }
       } catch (UnsupportedFlavorException e) {
       } catch (IOException e) {
       }
       if (textdata.equals("")) {
         IJ.error("Error copying from clipboard.");
         return;
       }
     } else {
       if (niframes[index] instanceof Editor) {
         Editor tw = (Editor) niframes[index];
         textdata = tw.getText();
       } else {
         if (niframes[index] instanceof TextWindow) {
           TextWindow tw = (TextWindow) niframes[index];
           textdata = tw.getTextPanel().getText();
         } else {
           IJ.showMessage("Not a valid text window");
           return;
         }
       }
     }
   }
   if (textdata == null) {
     IJ.showMessage("Error in Obtaining String");
     return;
   }
   if (textdata.indexOf("\r") >= 0) {
     textdata = textdata.replace('\r', '\n');
   }
   char[] delims = {'\t', ',', ' '};
   delimit_string ds = new delimit_string(delims[delimindex]);
   String[] rows = ds.getrows(textdata);
   int lines = rows.length;
   int columns = ds.getnumcolumns(rows[0]);
   int ycolumns = columns;
   if (hasxvals) {
     if (multix) {
       ycolumns /= 2;
     } else {
       ycolumns--;
     }
   }
   if (multix) {
     float[][] ydata = new float[ycolumns][lines];
     float[][] xdata = new float[ycolumns][lines];
     for (int i = 0; i < lines; i++) {
       float[] temp = ds.delim2float(rows[i], columns);
       for (int j = 0; j < ycolumns; j++) {
         ydata[j][i] = temp[2 * j + 1];
         xdata[j][i] = temp[2 * j];
       }
     }
     int[] npts = new int[ycolumns];
     for (int i = 0; i < ycolumns; i++) {
       npts[i] = lines;
     }
     if (skipendzeros) {
       for (int i = 0; i < ycolumns; i++) {
         int counter = lines - 1;
         while ((xdata[i][counter] == 0.0f || Float.isNaN(xdata[i][counter])) && counter > 0) {
           xdata[i][counter] = 0.0f;
           ydata[i][counter] = 0.0f;
           npts[i]--;
           counter--;
         }
       }
     }
     (new PlotWindow4("Text Plot", "x", "y", xdata, ydata, npts)).draw();
   } else {
     float[][] tempydata = new float[ycolumns][lines];
     float[] tempxdata = new float[lines];
     float[][] xdata = null;
     float[][] ydata = null;
     int startcolumn = 0;
     if (hasxvals) startcolumn = 1;
     for (int i = 0; i < lines; i++) {
       float[] temp = ds.delim2float(rows[i], columns);
       if (hasxvals) {
         tempxdata[i] = temp[0];
       } else {
         tempxdata[i] = (float) (i + 1);
       }
       for (int j = 0; j < ycolumns; j++) {
         tempydata[j][i] = temp[j + startcolumn];
       }
     }
     int[] npts = new int[ycolumns];
     npts[0] = lines;
     if (skipendzeros) {
       int maxpts = 0;
       for (int i = 0; i < ycolumns; i++) {
         int counter = lines - 1;
         npts[i] = lines;
         while ((tempydata[i][counter] == 0.0f || Float.isNaN(tempydata[i][counter]))
             && counter > 0) {
           npts[i]--;
           counter--;
         }
         if (npts[i] > maxpts) maxpts = npts[i];
         IJ.log("" + npts[i]);
       }
       ydata = new float[ycolumns][maxpts];
       xdata = new float[ycolumns][maxpts];
       for (int i = 0; i < ycolumns; i++) {
         // npts[i]=npts[0];
         System.arraycopy(tempxdata, 0, xdata[i], 0, npts[i]);
         System.arraycopy(tempydata[i], 0, ydata[i], 0, npts[i]);
       }
     } else {
       ydata = tempydata;
       xdata = new float[ycolumns][];
       for (int i = 0; i < ycolumns; i++) {
         npts[i] = npts[0];
         xdata[i] = tempxdata.clone();
       }
     }
     (new PlotWindow4("Text Plot", "x", "y", xdata, ydata, npts)).draw();
   }
 }
コード例 #24
0
    public BandAdjuster() {

      super("Threshold Colour");
      if (instance != null) {
        instance.toFront();
        return;
      }
      imp = WindowManager.getCurrentImage();
      if (imp == null) {
        IJ.beep();
        IJ.showStatus("No image");
        return;
      }
      IJ.run("Select None");
      thread = new Thread(this, "BandAdjuster");
      WindowManager.addWindow(this);
      instance = this;
      IJ.register(PasteController.class);

      ij = IJ.getInstance();
      Font font = new Font("SansSerif", Font.PLAIN, 10);
      GridBagLayout gridbag = new GridBagLayout();
      GridBagConstraints c = new GridBagConstraints();
      setLayout(gridbag);

      int y = 0;
      c.gridx = 0;
      c.gridy = y;
      c.gridwidth = 1;
      c.weightx = 0;
      c.insets = new Insets(5, 0, 0, 0);
      labelh = new Label("Hue", Label.CENTER);
      add(labelh, c);

      c.gridx = 1;
      c.gridy = y++;
      c.gridwidth = 1;
      c.weightx = 0;
      c.insets = new Insets(7, 0, 0, 0);
      labelf = new Label("Filter type", Label.RIGHT);
      add(labelf, c);

      // plot
      c.gridx = 0;
      c.gridy = y;
      c.gridwidth = 1;
      c.fill = c.BOTH;
      c.anchor = c.CENTER;
      c.insets = new Insets(0, 5, 0, 0);
      add(plot, c);

      // checkboxes
      panelh = new Panel();
      filterTypeH = new CheckboxGroup();
      bandPassH = new Checkbox("Pass");
      bandPassH.setCheckboxGroup(filterTypeH);
      bandPassH.addItemListener(this);
      panelh.add(bandPassH);
      bandStopH = new Checkbox("Stop");
      bandStopH.setCheckboxGroup(filterTypeH);
      bandStopH.addItemListener(this);
      panelh.add(bandStopH);
      bandPassH.setState(true);
      c.gridx = 1;
      c.gridy = y++;
      c.gridwidth = 2;
      c.insets = new Insets(5, 0, 0, 0);
      add(panelh, c);

      // minHue slider
      minSlider = new Scrollbar(Scrollbar.HORIZONTAL, 0, 1, 0, sliderRange);
      c.gridx = 0;
      c.gridy = y++;
      c.gridwidth = 1;
      c.weightx = IJ.isMacintosh() ? 90 : 100;
      c.fill = c.HORIZONTAL;
      c.insets = new Insets(5, 5, 0, 0);

      add(minSlider, c);
      minSlider.addAdjustmentListener(this);
      minSlider.setUnitIncrement(1);

      // minHue slider label
      c.gridx = 1;
      c.gridwidth = 1;
      c.weightx = IJ.isMacintosh() ? 10 : 0;
      c.insets = new Insets(5, 0, 0, 0);
      label1 = new Label("       ", Label.LEFT);
      label1.setFont(font);
      add(label1, c);

      // maxHue sliderHue
      maxSlider = new Scrollbar(Scrollbar.HORIZONTAL, 0, 1, 0, sliderRange);
      c.gridx = 0;
      c.gridy = y;
      c.gridwidth = 1;
      c.weightx = 100;
      c.insets = new Insets(5, 5, 0, 0);
      add(maxSlider, c);
      maxSlider.addAdjustmentListener(this);
      maxSlider.setUnitIncrement(1);

      // maxHue slider label
      c.gridx = 1;
      c.gridwidth = 1;
      c.gridy = y++;
      c.weightx = 0;
      c.insets = new Insets(5, 0, 0, 0);
      label2 = new Label("       ", Label.LEFT);
      label2.setFont(font);
      add(label2, c);

      // =====
      c.gridx = 0;
      c.gridy = y++;
      c.gridwidth = 1;
      c.weightx = 0;
      c.insets = new Insets(10, 0, 0, 0);
      labels = new Label("Saturation", Label.CENTER);
      add(labels, c);

      // plot
      c.gridx = 0;
      c.gridy = y;
      c.gridwidth = 1;
      c.fill = c.BOTH;
      c.anchor = c.CENTER;
      c.insets = new Insets(0, 5, 0, 0);
      add(splot, c);

      // checkboxes
      panels = new Panel();
      filterTypeS = new CheckboxGroup();
      bandPassS = new Checkbox("Pass");
      bandPassS.setCheckboxGroup(filterTypeS);
      bandPassS.addItemListener(this);
      panels.add(bandPassS);
      bandStopS = new Checkbox("Stop");
      bandStopS.setCheckboxGroup(filterTypeS);
      bandStopS.addItemListener(this);
      panels.add(bandStopS);
      bandPassS.setState(true);
      c.gridx = 1;
      c.gridy = y++;
      c.gridwidth = 2;
      c.insets = new Insets(5, 0, 0, 0);
      add(panels, c);

      // minSat slider
      minSlider2 = new Scrollbar(Scrollbar.HORIZONTAL, 0, 1, 0, sliderRange);
      c.gridx = 0;
      c.gridy = y++;
      c.gridwidth = 1;
      c.weightx = IJ.isMacintosh() ? 90 : 100;
      c.fill = c.HORIZONTAL;
      c.insets = new Insets(5, 5, 0, 0);
      add(minSlider2, c);
      minSlider2.addAdjustmentListener(this);
      minSlider2.setUnitIncrement(1);

      // minSat slider label
      c.gridx = 1;
      c.gridwidth = 1;
      c.weightx = IJ.isMacintosh() ? 10 : 0;
      c.insets = new Insets(5, 0, 0, 0);
      label3 = new Label("       ", Label.LEFT);
      label3.setFont(font);
      add(label3, c);

      // maxSat slider
      maxSlider2 = new Scrollbar(Scrollbar.HORIZONTAL, 0, 1, 0, sliderRange);
      c.gridx = 0;
      c.gridy = y++;
      c.gridwidth = 1;
      c.weightx = 100;
      c.insets = new Insets(5, 5, 0, 0);
      add(maxSlider2, c);
      maxSlider2.addAdjustmentListener(this);
      maxSlider2.setUnitIncrement(1);

      // maxSat slider label
      c.gridx = 1;
      c.gridwidth = 1;
      c.weightx = 0;
      c.insets = new Insets(5, 0, 0, 0);
      label4 = new Label("       ", Label.LEFT);
      label4.setFont(font);
      add(label4, c);

      // =====
      c.gridx = 0;
      c.gridwidth = 1;
      c.gridy = y++;
      c.weightx = 0;
      c.insets = new Insets(10, 0, 0, 0);
      labelb = new Label("Brightness", Label.CENTER);
      add(labelb, c);

      c.gridx = 0;
      c.gridwidth = 1;
      c.gridy = y;
      c.fill = c.BOTH;
      c.anchor = c.CENTER;
      c.insets = new Insets(0, 5, 0, 0);
      add(bplot, c);

      // checkboxes
      panelb = new Panel();
      filterTypeB = new CheckboxGroup();
      bandPassB = new Checkbox("Pass");
      bandPassB.setCheckboxGroup(filterTypeB);
      bandPassB.addItemListener(this);
      panelb.add(bandPassB);
      bandStopB = new Checkbox("Stop");
      bandStopB.setCheckboxGroup(filterTypeB);
      bandStopB.addItemListener(this);
      panelb.add(bandStopB);
      bandPassB.setState(true);
      c.gridx = 1;
      c.gridy = y++;
      c.gridwidth = 2;
      c.insets = new Insets(5, 0, 0, 0);
      add(panelb, c);

      // minBri slider
      minSlider3 = new Scrollbar(Scrollbar.HORIZONTAL, 0, 1, 0, sliderRange);
      c.gridx = 0;
      c.gridy = y++;
      c.gridwidth = 1;
      c.weightx = IJ.isMacintosh() ? 90 : 100;
      c.fill = c.HORIZONTAL;
      c.insets = new Insets(5, 5, 0, 0);
      add(minSlider3, c);
      minSlider3.addAdjustmentListener(this);
      minSlider3.setUnitIncrement(1);

      // minBri slider label
      c.gridx = 1;
      c.gridwidth = 1;
      c.weightx = IJ.isMacintosh() ? 10 : 0;
      c.insets = new Insets(5, 0, 0, 0);
      label5 = new Label("       ", Label.LEFT);
      label5.setFont(font);
      add(label5, c);

      // maxBri slider
      maxSlider3 = new Scrollbar(Scrollbar.HORIZONTAL, 0, 1, 0, sliderRange);
      c.gridx = 0;
      c.gridy = y++;
      c.gridwidth = 1;
      c.weightx = 100;
      c.insets = new Insets(5, 5, 0, 0);
      add(maxSlider3, c);
      maxSlider3.addAdjustmentListener(this);
      maxSlider3.setUnitIncrement(1);

      // maxBri slider label
      c.gridx = 1;
      c.gridwidth = 1;
      c.weightx = 0;
      c.insets = new Insets(5, 0, 0, 0);
      label6 = new Label("       ", Label.LEFT);
      label6.setFont(font);
      add(label6, c);

      // =====
      panelt = new Panel();
      threshold = new Checkbox("Threshold");
      threshold.addItemListener(this);
      panelt.add(threshold);

      invert = new Checkbox("Invert");
      invert.addItemListener(this);
      panelt.add(invert);

      c.gridx = 0;
      c.gridy = y++;
      c.gridwidth = 2;
      c.insets = new Insets(0, 0, 0, 0);
      add(panelt, c);

      // buttons
      panel = new Panel();
      // panel.setLayout(new GridLayout(2, 2, 0, 0));
      originalB = new Button("Original");
      originalB.setEnabled(false);
      originalB.addActionListener(this);
      originalB.addKeyListener(ij);
      panel.add(originalB);

      filteredB = new Button("Filtered");
      filteredB.setEnabled(false);
      filteredB.addActionListener(this);
      filteredB.addKeyListener(ij);
      panel.add(filteredB);

      stackB = new Button("Stack");
      stackB.addActionListener(this);
      stackB.addKeyListener(ij);
      panel.add(stackB);

      helpB = new Button("Help");
      helpB.addActionListener(this);
      helpB.addKeyListener(ij);
      panel.add(helpB);

      c.gridx = 0;
      c.gridy = y++;
      c.gridwidth = 2;
      c.insets = new Insets(0, 0, 0, 0);
      add(panel, c);

      panelMode = new Panel();

      sampleB = new Button("Sample");
      sampleB.addActionListener(this);
      sampleB.addKeyListener(ij);
      panelMode.add(sampleB);

      colourMode = new CheckboxGroup();
      hsb = new Checkbox("HSB");
      hsb.setCheckboxGroup(colourMode);
      hsb.addItemListener(this);
      panelMode.add(hsb);
      hsb.setState(true);
      rgb = new Checkbox("RGB");
      rgb.setCheckboxGroup(colourMode);
      rgb.addItemListener(this);
      panelMode.add(rgb);

      c.gridx = 0;
      c.gridy = y++;
      c.gridwidth = 2;
      c.insets = new Insets(0, 0, 0, 0);
      add(panelMode, c);

      addKeyListener(ij); // ImageJ handles keyboard shortcuts
      pack();
      GUI.center(this);
      setVisible(true);

      ip = setup(imp);
      if (ip == null) {
        imp.unlock();
        IJ.beep();
        IJ.showStatus("RGB image cannot be thresholded");
        return;
      }
      thread.start();
    }
コード例 #25
0
  public void run(String arg) {
    GenericDialog gd = new GenericDialog("Options");
    gd.addCheckbox("Acceptor_First", true);
    gd.showDialog();
    if (gd.wasCanceled()) return;
    boolean a1 = gd.getNextBoolean();
    int asp = 0;
    int dsp = 1;
    int aop = 2;
    int dop = 3;
    int atp = 4;
    int dtp = 5;
    if (!a1) {
      asp = 1;
      dsp = 0;
      aop = 3;
      dop = 2;
      atp = 5;
      dtp = 4;
    }
    ImageWindow iw = WindowManager.getCurrentWindow();
    float[][] xvals = (float[][]) jutils.runPW4VoidMethod(iw, "getXValues");
    float[][] yvals = (float[][]) jutils.runPW4VoidMethod(iw, "getYValues");
    int[] npts = (int[]) jutils.runPW4VoidMethod(iw, "getNpts");
    int maxpts = (int) jstatistics.getstatistic("Max", npts, null);
    int nsets = npts.length / 6;
    float[][] rtxvals = new float[nsets][maxpts];
    float[][] rtavals = new float[nsets][maxpts];
    float[][] rtdvals = new float[nsets][maxpts];
    int[] rtnpts = new int[nsets];
    int fretlength = 10;
    float[][] stfretvals = new float[nsets][fretlength];
    float[][] offfretvals = new float[nsets][fretlength];
    TextWindow tw = jutils.selectTable("DNA Damage FRET");
    if (tw == null)
      tw =
          new TextWindow(
              "DNA Damage FRET",
              "title\tacceptor\tdonor\testripe\teoff\tmaxart\tmaxdrt",
              "",
              400,
              200);
    // note that st stands for stripe and off is for areas off the damage stripe
    for (int i = 0; i < npts.length / 6; i++) {
      int len = npts[i * 6];
      int damageindex = findbleach(yvals[i * 6 + dsp], len);
      int fretindex = findbleach(yvals[i * 6 + atp], len);
      IJ.log("set " + i + " damage pos = " + damageindex + " , fret pos = " + fretindex);
      int predamagestart = damageindex - 4;
      int prefretstart = fretindex - 5;
      float staccpredam = getavg(yvals[i * 6 + asp], len, predamagestart, damageindex - 1);
      float stdonpredam = getavg(yvals[i * 6 + dsp], len, predamagestart, damageindex - 1);
      float nucaccpredam = getavg(yvals[i * 6 + atp], len, predamagestart, damageindex - 1);
      float nucdonpredam = getavg(yvals[i * 6 + dtp], len, predamagestart, damageindex - 1);
      float stdonprefret = getavg(yvals[i * 6 + dsp], len, prefretstart, fretindex - 2);
      float stdonafret = getavg(yvals[i * 6 + dsp], len, fretindex, fretindex + 3);
      float offdonprefret = getavg(yvals[i * 6 + dop], len, prefretstart, fretindex - 2);
      float offdonafret = getavg(yvals[i * 6 + dop], len, fretindex, fretindex + 3);
      float estripe = 1.0f - stdonprefret / stdonafret;
      float eoff = 1.0f - offdonprefret / offdonafret;
      rtnpts[i] = len;
      for (int j = 0; j < len; j++) {
        rtxvals[i][j] = j - damageindex - 1;
        rtavals[i][j] =
            (yvals[i * 6 + asp][j] / staccpredam) / (yvals[i * 6 + atp][j] / nucaccpredam);
        rtdvals[i][j] =
            (yvals[i * 6 + dsp][j] / stdonpredam) / (yvals[i * 6 + dtp][j] / nucdonpredam);
      }
      float[] smart = (float[]) algutils.get_subarray(rtavals[i], 0, fretindex);
      float[] smdrt = (float[]) algutils.get_subarray(rtdvals[i], 0, fretindex);
      jsmooth.blur1D(smart, 2.0f);
      jsmooth.blur1D(smdrt, 2.0f);
      float maxart = 0.0f;
      float maxdrt = 0.0f;
      for (int j = 0; j < fretindex - 2; j++) {
        if (smart[j] > maxart) maxart = smart[j];
        if (smdrt[j] > maxdrt) maxdrt = smdrt[j];
      }

      stfretvals[i] = getregion(yvals[i * 6 + dsp], len, prefretstart, fretlength);
      offfretvals[i] = getregion(yvals[i * 6 + dop], len, prefretstart, fretlength);
      tw.append(
          iw.getTitle()
              + "-"
              + (i + 1)
              + "\t"
              + staccpredam
              + "\t"
              + stdonpredam
              + "\t"
              + estripe
              + "\t"
              + eoff
              + "\t"
              + maxart
              + "\t"
              + maxdrt);
    }
    new PlotWindow4("Stripe_FRET_profiles", "time", "intensity", stfretvals, null).draw();
    new PlotWindow4("OffStripe_FRET_profiles", "time", "intensity", offfretvals, null).draw();
    new PlotWindow4("Acc_Rt_profiles", "time", "intensity", rtxvals, rtavals, rtnpts).draw();
    new PlotWindow4("Don_Rt_profiles", "time", "intensity", rtxvals, rtdvals, rtnpts).draw();
  }
コード例 #26
0
	public void run(String arg) {

  int[] wList = WindowManager.getIDList();
        if (wList==null) {
            IJ.error("No images are open.");
            return;
        }
	double kernel=3;
	double kernelsum = 0;
	double kernelvarsum =0;
	double kernalvar = 0;
	double sigmawidth = 2;
	int kernelindex, minpixnumber;
	String[] kernelsize =  { "3�,"5�, "7�, "9�};

	GenericDialog gd = new GenericDialog("Sigma Filter");
	gd.addChoice("Kernel size", kernelsize, kernelsize[0]);
	gd.addNumericField("Sigma width",sigmawidth , 2);
	gd.addNumericField("Minimum number of pixels", 1, 0);

	gd.addCheckbox("Keep source:",true);
	gd.addCheckbox("Do all stack:",true);
	gd.addCheckbox("Modified Lee's FIlter:",true);
	       	
	gd.showDialog();
       	if (gd.wasCanceled()) return ;
	kernelindex =  gd.getNextChoiceIndex();
          	sigmawidth = gd.getNextNumber();
          	minpixnumber = ((int)gd.getNextNumber());
          	boolean keep = gd.getNextBoolean();
	boolean doallstack = gd.getNextBoolean();
	boolean modified = gd.getNextBoolean();
	if (kernelindex==0) kernel = 3;
	if (kernelindex==1) kernel = 5;
	if (kernelindex==2) kernel = 7;
	if (kernelindex==3) kernel = 9;
    	long start = System.currentTimeMillis();
	
if (minpixnumber> (kernel*kernel)){
	      IJ.showMessage("Sigma filter", "There must be more pixels in the kernel than+\n" + "the minimum number to be included");
            return;
        }
	double v, midintensity;
	int   x, y, ix, iy;
	double sum = 0;
	double backupsum =0;
	int count = 0;
	int n = 0;
	if (keep) {IJ.run("Select All"); IJ.run("Duplicate...", "title='Sigma filtered' duplicate");}

	int radius = (int)(kernel-1)/2;
	ImagePlus imp = WindowManager.getCurrentImage();
	ImageStack stack1 = imp.getStack();
	int width = imp.getWidth();
	int height = imp.getHeight();
	int nslices = stack1.getSize();
	int cslice = imp.getCurrentSlice();
	double status = width*height*nslices;
	
	ImageProcessor  ip = imp.getProcessor();
	int sstart = 1;
	if (!doallstack) {sstart = cslice; nslices=sstart;status = status/nslices;};

 for (int i=sstart; i<=nslices; i++) {
                imp.setSlice(i);
                    
for (x=radius;x<width+radius;x++)	{
		for (y=radius;y<height+radius;y++)	{
			
			midintensity = ip.getPixelValue(x,y);
			count = 0;
			sum = 0;
			kernelsum =0;
			kernalvar =0;
			kernelvarsum =0;
			backupsum = 0;

		//calculate mean of kernel value
			for (ix=0;ix<kernel;ix++)	{
					for (iy=0;iy<kernel;iy++)	{
							v = ip.getPixelValue(x+ix-radius,y+iy-radius);
							kernelsum = kernelsum+v;
								}
						}
			double sigmacalcmean = (kernelsum/(kernel*kernel));

		//calculate variance of kernel
			for (ix=0;ix<kernel;ix++)	{
					for (iy=0;iy<kernel;iy++)	{
							v = ip.getPixelValue(x+ix-radius,y+iy-radius);
							kernalvar = (v-sigmacalcmean)*(v-sigmacalcmean);
							kernelvarsum = kernelvarsum + kernalvar;
								}
						}
			//double variance = kernelvarsum/kernel;
			double sigmacalcvar = kernelvarsum/((kernel*kernel)-1);

			//calcuate sigma range = sqrt(variance/(mean^2)) � sigmawidth
			double sigmarange  = sigmawidth*(Math.sqrt((sigmacalcvar) /(sigmacalcmean*sigmacalcmean)));
			//calulate sigma top value and bottom value
			double sigmatop = midintensity*(1+sigmarange);
			double sigmabottom = midintensity*(1-sigmarange);
			//calculate mean of values that differ are in sigma range.
			for (ix=0;ix<kernel;ix++)	{
					for (iy=0;iy<kernel;iy++)	{
							v = ip.getPixelValue(x+ix-radius,y+iy-radius);
							if ((v>=sigmabottom)&&(v<=sigmatop)){
								sum = sum+v;
								count = count+1;   }
								backupsum = v+ backupsum;
										}		
						}
//if there are too few pixels in the kernal that are within sigma range, the 
//mean of the entire kernal is taken. My modification of Lee's filter is to exclude the central value 
//from the calculation of the mean as I assume it to be spuriously high or low 
			if (!(count>(minpixnumber)))
				{sum = (backupsum-midintensity);
				count = (int)((kernel*kernel)-1);
				if (!modified)
					{sum = (backupsum);
					count  = (int)(kernel*kernel);}
				}
			
			double val =  (sum/count);
			ip.putPixelValue(x,y, val);
			n = n+1;
	double percentage = (((double)n/status)*100);
			 IJ.showStatus(IJ.d2s(percentage,0) +"% done");		
			
}

	//		IJ.showProgress(i, status);
					}}
			imp.updateAndDraw();
 			IJ.showStatus(IJ.d2s((System.currentTimeMillis()-start)/1000.0, 2)+" seconds");        }      
コード例 #27
0
 /** Closes this window. */
 public void close() {
   // setVisible(false);
   dispose();
   WindowManager.removeWindow(this);
 }
コード例 #28
0
  public void run(String arg) {
    GenericDialog gd = new GenericDialog("Options");
    double sfreq = 20000.0;
    gd.addNumericField("Sampling Frequency?", sfreq, 1, 10, null);
    String[] psfchoice = {"3D Gaussian", "Gaus-Lorentz^2", "2D Gaussian"};
    gd.addChoice("PSF Type?", psfchoice, psfchoice[0]);
    String[] filetypechoice = {
      "Confocor 3 raw", "Short binary trajectory", "PlotWindow trajectory", "Ascii Text File"
    };
    gd.addChoice("File Type?", filetypechoice, filetypechoice[0]);
    boolean ch2green = true;
    gd.addCheckbox("Ch2 is green?", ch2green);
    gd.showDialog();
    if (gd.wasCanceled()) {
      return;
    }
    sfreq = gd.getNextNumber();
    int psfflag = gd.getNextChoiceIndex();
    int fileflag = gd.getNextChoiceIndex();
    ch2green = gd.getNextBoolean();
    int nfiles = 0;
    Object[] histograms = null;
    int xmax = 0;
    int ymax = 0;
    String[] names = null;
    if (fileflag < 2) {
      jdataio ioclass = new jdataio();
      File[] filearray = ioclass.openfiles(OpenDialog.getDefaultDirectory(), IJ.getInstance());
      if (filearray.length == 0) {
        return;
      }
      String dir = filearray[0].getAbsolutePath();
      int sepindex = dir.lastIndexOf(File.separator);
      String newdir = dir.substring(0, sepindex + 1);
      OpenDialog.setDefaultDirectory(newdir);
      nfiles = filearray.length / 2;
      if (nfiles > 25) {
        nfiles = 25;
      }
      histograms = new Object[nfiles];
      names = organize_c3_files(filearray);
      for (int i = 0; i < nfiles; i++) {
        try {
          int length1 = (int) (((double) filearray[2 * i].length() - 128.0) / 4.0);
          int length2 = (int) (((double) filearray[2 * i + 1].length() - 128.0) / 4.0);
          int length3 = (int) (((double) filearray[2 * i].length()) / 2.0);
          int length4 = (int) (((double) filearray[2 * i + 1].length()) / 2.0);
          InputStream instream = new BufferedInputStream(new FileInputStream(filearray[2 * i]));
          InputStream instream2 =
              new BufferedInputStream(new FileInputStream(filearray[2 * i + 1]));
          if (fileflag == 0) {
            int[] pmdata = new int[length1];
            int[] pmdata2 = new int[length2];
            if (!ioclass.skipstreambytes(instream, 128)) {
              showioerror();
              instream.close();
              return;
            }
            if (!ioclass.skipstreambytes(instream2, 128)) {
              showioerror();
              instream2.close();
              return;
            }
            if (!ioclass.readintelintfile(instream, length1, pmdata)) {
              showioerror();
              instream.close();
              return;
            }
            if (!ioclass.readintelintfile(instream2, length2, pmdata2)) {
              showioerror();
              instream2.close();
              return;
            }
            if (ch2green) {
              histograms[i] = (new pmodeconvert()).pm2pch(pmdata2, pmdata, sfreq, 20000000);
            } else {
              histograms[i] = (new pmodeconvert()).pm2pch(pmdata, pmdata2, sfreq, 20000000);
            }
          } else {
            float[] tmdata = new float[length3];
            float[] tmdata2 = new float[length4];
            if (!ioclass.readintelshortfile(instream, length3, tmdata)) {
              showioerror();
              instream.close();
              return;
            }
            if (!ioclass.readintelshortfile(instream2, length4, tmdata2)) {
              showioerror();
              instream2.close();
              return;
            }
            if (ch2green) {
              histograms[i] = (new pmodeconvert()).create_2Dhistogram(tmdata2, tmdata);
            } else {
              histograms[i] = (new pmodeconvert()).create_2Dhistogram(tmdata, tmdata2);
            }
          }
          if (((float[][]) histograms[i]).length > xmax) {
            xmax = ((float[][]) histograms[i]).length;
          }
          if (((float[][]) histograms[i])[0].length > ymax) {
            ymax = ((float[][]) histograms[i])[0].length;
          }
          instream.close();
          instream2.close();
        } catch (IOException e) {
          showioerror();
          return;
        }
      }
    } else {
      if (fileflag == 2) {
        ImageWindow iw = WindowManager.getCurrentWindow();
        float[][] trajectories = (float[][]) jutils.runPW4VoidMethod(iw, "getYValues");
        float[][] tempxvals = (float[][]) jutils.runPW4VoidMethod(iw, "getXValues");
        sfreq = 1.0 / ((double) tempxvals[0][1]);
        nfiles = trajectories.length / 2;
        if (nfiles > 25) {
          nfiles = 25;
        }
        names = new String[nfiles + 1];
        names[nfiles] = "avg";
        histograms = new Object[nfiles];
        for (int i = 0; i < nfiles; i++) {
          names[i] = "trajectory " + (i + 1);
          if (ch2green) {
            histograms[i] =
                (new pmodeconvert())
                    .create_2Dhistogram(trajectories[2 * i + 1], trajectories[2 * i]);
          } else {
            histograms[i] =
                (new pmodeconvert())
                    .create_2Dhistogram(trajectories[2 * i], trajectories[2 * i + 1]);
          }
          if (((float[][]) histograms[i]).length > xmax) {
            xmax = ((float[][]) histograms[i]).length;
          }
          if (((float[][]) histograms[i])[0].length > ymax) {
            ymax = ((float[][]) histograms[i])[0].length;
          }
        }
      } else {
        // here we read tab delimited lines from files
        jdataio ioclass = new jdataio();
        File[] filearray = ioclass.openfiles(OpenDialog.getDefaultDirectory(), IJ.getInstance());
        if (filearray.length == 0) {
          return;
        }
        String dir = filearray[0].getAbsolutePath();
        int sepindex = dir.lastIndexOf(File.separator);
        String newdir = dir.substring(0, sepindex + 1);
        OpenDialog.setDefaultDirectory(newdir);
        nfiles = filearray.length;
        if (nfiles > 25) {
          nfiles = 25;
        }
        histograms = new Object[nfiles];
        names = new String[nfiles + 1];
        names[nfiles] = "avg";
        for (int i = 0; i < nfiles; i++) {
          try {
            names[i] = filearray[i].getName();
            BufferedReader d = new BufferedReader(new FileReader(filearray[i]));
            String[] lines = new String[256];
            int counter = 0;
            do {
              lines[counter] = d.readLine();
              counter++;
            } while ((lines[counter - 1] != null && lines[counter - 1] != "") && counter < 256);
            int numcolumns = 0;
            for (int j = 0; j < counter - 1; j++) {
              int temp = getncolumns(lines[j]);
              if (temp > numcolumns) {
                numcolumns = temp;
              }
            }
            float[][] temphist2 = null;
            if (ch2green) {
              temphist2 = new float[numcolumns][counter - 1];
            } else {
              temphist2 = new float[counter - 1][numcolumns];
            }
            for (int k = 0; k < counter - 1; k++) {
              float[] temp = tab_delim2float(lines[k]);
              for (int j = 0; j < numcolumns; j++) {
                if (ch2green) {
                  temphist2[j][k] = temp[j];
                } else {
                  temphist2[k][j] = temp[j];
                }
              }
            }
            histograms[i] = temphist2;
            d.close();
          } catch (IOException e) {
            showioerror();
            return;
          }
        }
        for (int i = 0; i < nfiles; i++) {
          if (((float[][]) histograms[i]).length > xmax) {
            xmax = ((float[][]) histograms[i]).length;
          }
          if (((float[][]) histograms[i])[0].length > ymax) {
            ymax = ((float[][]) histograms[i])[0].length;
          }
        }
      }
    }
    // note that here x is green and y is red
    float[][][] pch = new float[nfiles][xmax][ymax];
    for (int i = 0; i < nfiles; i++) {
      for (int j = 0; j < ((float[][]) histograms[i]).length; j++) {
        for (int k = 0; k < ((float[][]) histograms[i])[j].length; k++) {
          pch[i][j][k] = ((float[][]) histograms[i])[j][k];
        }
      }
    }

    final PCH2DFitWindow cw = new PCH2DFitWindow();
    cw.init(names, pch, psfflag);

    final Frame f = new Frame("PCH 2D Analysis");
    f.setLocation(10, 10);
    f.addWindowListener(
        new WindowAdapter() {
          public void windowClosing(WindowEvent e) {
            f.dispose();
          }
        });

    f.add(cw);
    f.pack();
    f.setResizable(false);
    Insets ins = f.getInsets();
    cw.totalSize.height = PCH2DFitWindow.H + ins.bottom + ins.top + 65;
    cw.totalSize.width = PCH2DFitWindow.WR + ins.left + ins.right;
    f.setSize(cw.totalSize);
    f.setVisible(true);
    cw.requestFocus();
  }
コード例 #29
0
 public void focusGained(FocusEvent e) {
   WindowManager.setWindow(this);
 }