Exemplo n.º 1
0
 void addToRoiManager(ImagePlus imp) {
   if (IJ.macroRunning() && Interpreter.isBatchModeRoiManager())
     IJ.error("run(\"Add to Manager\") may not work in batch mode macros");
   Frame frame = WindowManager.getFrame("ROI Manager");
   if (frame == null) IJ.run("ROI Manager...");
   if (imp == null) return;
   Roi roi = imp.getRoi();
   if (roi == null) return;
   frame = WindowManager.getFrame("ROI Manager");
   if (frame == null || !(frame instanceof RoiManager)) IJ.error("ROI Manager not found");
   RoiManager rm = (RoiManager) frame;
   boolean altDown = IJ.altKeyDown();
   IJ.setKeyUp(IJ.ALL_KEYS);
   if (altDown && !IJ.macroRunning()) IJ.setKeyDown(KeyEvent.VK_SHIFT);
   if (roi.getState() == Roi.CONSTRUCTING) { // wait (up to 2 sec.) until ROI finished
     long start = System.currentTimeMillis();
     while (true) {
       IJ.wait(10);
       if (roi.getState() != Roi.CONSTRUCTING) break;
       if ((System.currentTimeMillis() - start) > 2000) {
         IJ.beep();
         IJ.error("Add to Manager", "Selection is not complete");
         return;
       }
     }
   }
   rm.runCommand("add");
   IJ.setKeyUp(IJ.ALL_KEYS);
 }
Exemplo n.º 2
0
 void loadTransformation(String filename, ResultsTable res) {
   try {
     String line;
     FileReader fr = new FileReader(filename);
     BufferedReader br = new BufferedReader(fr);
     if (!br.readLine().equals(" 	Z-Step	Raw Width minus Heigh	Calibration Width minus Height")) {
       IJ.error("File does not seam to be an Astigmatism calibration file");
       return;
     }
     // java.lang.String [] elements = new java.lang.String [3];
     java.lang.String[] elements;
     int counter = 1;
     res.reset();
     while ((line = br.readLine()) != null) {
       IJ.showStatus("Loading element " + counter + "... sit back and relax.");
       counter++;
       line.trim();
       elements = line.split("\t");
       res.incrementCounter();
       res.addValue("Z-Step", Double.parseDouble(elements[1]));
       res.addValue("Raw Width minus Heigh", Double.parseDouble(elements[2]));
       res.addValue("Calibration Width minus Height", Double.parseDouble(elements[3]));
     }
     fr.close();
   } catch (FileNotFoundException e) {
     IJ.error("File not found exception" + e);
     return;
   } catch (IOException e) {
     IJ.error("IOException exception" + e);
     return;
   } catch (NumberFormatException e) {
     IJ.error("Number format exception" + e);
     return;
   }
 }
Exemplo n.º 3
0
  public boolean beadCalibration3d() {
    imp = IJ.getImage();
    if (imp == null) {
      IJ.noImage();
      return false;
    } else if (imp.getStackSize() == 1) {
      IJ.error("Stack required");
      return false;
    } else if (imp.getType() != ImagePlus.GRAY8 && imp.getType() != ImagePlus.GRAY16) {
      // In order to support 32bit images, pict[] must be changed to float[], and  getPixel(x, y);
      // requires a Float.intBitsToFloat() conversion
      IJ.error("8 or 16 bit greyscale image required");
      return false;
    }
    width = imp.getWidth();
    height = imp.getHeight();
    nslices = imp.getStackSize();
    imtitle = imp.getTitle();

    models[0] = "*None*";
    models[1] = "line";
    models[2] = "2nd degree polynomial";
    models[3] = "3rd degree polynomial";
    models[4] = "4th degree polynomial";

    GenericDialog gd = new GenericDialog("3D PALM calibration");
    gd.addNumericField("Maximum FWHM (in px)", prefs.get("QuickPALM.3Dcal_fwhm", 20), 0);
    gd.addNumericField(
        "Particle local threshold (% maximum intensity)", prefs.get("QuickPALM.pthrsh", 20), 0);
    gd.addNumericField("Z-spacing (nm)", prefs.get("QuickPALM.z-step", 10), 2);
    gd.addNumericField("Calibration Z-smoothing (radius)", prefs.get("QuickPALM.window", 1), 0);
    gd.addChoice("Model", models, prefs.get("QuickPALM.model", models[3]));
    gd.addCheckbox(
        "Show divergence of bead positions against model",
        prefs.get("QuickPALM.3Dcal_showDivergence", false));
    gd.addCheckbox("Show extra particle info", prefs.get("QuickPALM.3Dcal_showExtraInfo", false));
    gd.addMessage("\n\nDon't forget to save the table in the end...");
    gd.showDialog();
    if (gd.wasCanceled()) return false;
    fwhm = gd.getNextNumber();
    prefs.set("QuickPALM.QuickPALM.3Dcal_fwhm", fwhm);
    pthrsh = gd.getNextNumber() / 100;
    prefs.set("QuickPALM.pthrsh", pthrsh * 100);
    cal_z = gd.getNextNumber();
    prefs.set("QuickPALM.z-step", cal_z);
    window = (int) gd.getNextNumber();
    prefs.set("QuickPALM.window", window);
    model = gd.getNextChoice();
    prefs.set("QuickPALM.model", model);
    part_divergence = gd.getNextBoolean();
    prefs.set("QuickPALM.3Dcal_showDivergence", part_divergence);
    part_extrainfo = gd.getNextBoolean();
    prefs.set("QuickPALM.3Dcal_showExtraInfo", part_extrainfo);
    return true;
  }
Exemplo n.º 4
0
  /** Performs actual projection using specified method. */
  public void doProjection() {
    if (imp == null) return;
    sliceCount = 0;
    if (method < AVG_METHOD || method > MEDIAN_METHOD) method = AVG_METHOD;
    for (int slice = startSlice; slice <= stopSlice; slice += increment) sliceCount++;
    if (method == MEDIAN_METHOD) {
      projImage = doMedianProjection();
      return;
    }

    // Create new float processor for projected pixels.
    FloatProcessor fp = new FloatProcessor(imp.getWidth(), imp.getHeight());
    ImageStack stack = imp.getStack();
    RayFunction rayFunc = getRayFunction(method, fp);
    if (IJ.debugMode == true) {
      IJ.log("\nProjecting stack from: " + startSlice + " to: " + stopSlice);
    }

    // Determine type of input image. Explicit determination of
    // processor type is required for subsequent pixel
    // manipulation.  This approach is more efficient than the
    // more general use of ImageProcessor's getPixelValue and
    // putPixel methods.
    int ptype;
    if (stack.getProcessor(1) instanceof ByteProcessor) ptype = BYTE_TYPE;
    else if (stack.getProcessor(1) instanceof ShortProcessor) ptype = SHORT_TYPE;
    else if (stack.getProcessor(1) instanceof FloatProcessor) ptype = FLOAT_TYPE;
    else {
      IJ.error("Z Project", "Non-RGB stack required");
      return;
    }

    // Do the projection.
    for (int n = startSlice; n <= stopSlice; n += increment) {
      IJ.showStatus("ZProjection " + color + ": " + n + "/" + stopSlice);
      IJ.showProgress(n - startSlice, stopSlice - startSlice);
      projectSlice(stack.getPixels(n), rayFunc, ptype);
    }

    // Finish up projection.
    if (method == SUM_METHOD) {
      fp.resetMinAndMax();
      projImage = new ImagePlus(makeTitle(), fp);
    } else if (method == SD_METHOD) {
      rayFunc.postProcess();
      fp.resetMinAndMax();
      projImage = new ImagePlus(makeTitle(), fp);
    } else {
      rayFunc.postProcess();
      projImage = makeOutputImage(imp, fp, ptype);
    }

    if (projImage == null) IJ.error("Z Project", "Error computing projection.");
  }
Exemplo n.º 5
0
 void loadParticleResults(String filename, ResultsTable res) {
   try {
     String line;
     FileReader fr = new FileReader(filename);
     BufferedReader br = new BufferedReader(fr);
     java.lang.String header =
         " 	Intensity	X (px)	Y (px)	X (nm)	Y (nm)	Z (nm)	Left-Width(px)	Right-Width (px)	Up-Height (px)	Down-Height (px)	X Symmetry (%)	Y Symmetry (%)	Width minus Height (px)	Frame Number";
     java.lang.String firstline = br.readLine();
     if (!firstline.contains("X (px)	Y (px)	X (nm)	Y (nm)	Z (nm)")) {
       IJ.error("File does not seam to be a Particles Table file");
       IJ.log("Found header: " + firstline);
       IJ.log("Expecting: " + header);
       return;
     }
     res.reset();
     int counter = 1;
     java.util.concurrent.locks.Lock lock = new java.util.concurrent.locks.ReentrantLock();
     ThreadedLoader tloader = new ThreadedLoader();
     // java.lang.String txt = fr.read();
     while ((line = br.readLine()) != null) {
       tloader = new ThreadedLoader();
       tloader.mysetup(res, lock, line);
       tloader.start();
       IJ.showStatus("Loading particle " + counter + "... sit back and relax.");
       counter++;
     }
     try {
       tloader.join();
     } catch (Exception e) {
       IJ.error("" + e);
     }
     if (res.getCounter() < 5000000) {
       IJ.showStatus("Creating particle table, this should take a few seconds...");
       res.show("Results");
     } else
       IJ.showMessage(
           "Warning",
           "Results table has too many particles, they will not be shown but the data still exists within it\nyou can still use all the plugin functionality or save table changes though the 'Save Particle Table' command.");
     fr.close();
     IJ.showStatus("Done loading table...");
   } catch (FileNotFoundException e) {
     IJ.error("File not found exception" + e);
     return;
   } catch (IOException e) {
     IJ.error("IOException exception" + e);
     return;
   } catch (NumberFormatException e) {
     IJ.error("Number format exception" + e);
     return;
   }
 }
Exemplo n.º 6
0
  public boolean checkBeads() {
    rmanager = RoiManager.getInstance();
    if (IJ.versionLessThan("1.26i")) return false;
    else if (rmanager == null) {
      IJ.error("Add bead ROIs to the RoiManager first (select region then press [t]).");
      return false;
    }

    nrois = rmanager.getCount();
    if (nrois == 0) {
      IJ.error("Add bead ROIs to the RoiManager first (select region then press [t]).");
      return false;
    }
    rois = rmanager.getRoisAsArray();
    return true;
  }
Exemplo n.º 7
0
 void lineToArea(ImagePlus imp) {
   Roi roi = imp.getRoi();
   if (roi == null || !roi.isLine()) {
     IJ.error("Line to Area", "Line selection required");
     return;
   }
   Undo.setup(Undo.ROI, imp);
   Roi roi2 = null;
   if (roi.getType() == Roi.LINE) {
     double width = roi.getStrokeWidth();
     if (width <= 1.0) roi.setStrokeWidth(1.0000001);
     FloatPolygon p = roi.getFloatPolygon();
     roi.setStrokeWidth(width);
     roi2 = new PolygonRoi(p, Roi.POLYGON);
     roi2.setDrawOffset(roi.getDrawOffset());
   } else {
     ImageProcessor ip2 = new ByteProcessor(imp.getWidth(), imp.getHeight());
     ip2.setColor(255);
     roi.drawPixels(ip2);
     // new ImagePlus("ip2", ip2.duplicate()).show();
     ip2.setThreshold(255, 255, ImageProcessor.NO_LUT_UPDATE);
     ThresholdToSelection tts = new ThresholdToSelection();
     roi2 = tts.convert(ip2);
   }
   transferProperties(roi, roi2);
   roi2.setStrokeWidth(0);
   Color c = roi2.getStrokeColor();
   if (c != null) // remove any transparency
   roi2.setStrokeColor(new Color(c.getRed(), c.getGreen(), c.getBlue()));
   imp.setRoi(roi2);
   Roi.previousRoi = (Roi) roi.clone();
 }
Exemplo n.º 8
0
 void fitSpline() {
   Roi roi = imp.getRoi();
   if (roi == null) {
     noRoi("Spline");
     return;
   }
   int type = roi.getType();
   boolean segmentedSelection = type == Roi.POLYGON || type == Roi.POLYLINE;
   if (!(segmentedSelection
       || type == Roi.FREEROI
       || type == Roi.TRACED_ROI
       || type == Roi.FREELINE)) {
     IJ.error("Spline", "Polygon or polyline selection required");
     return;
   }
   if (roi instanceof EllipseRoi) return;
   PolygonRoi p = (PolygonRoi) roi;
   if (!segmentedSelection) {
     if (p.subPixelResolution()) p = trimFloatPolygon(p, p.getUncalibratedLength());
     else p = trimPolygon(p, p.getUncalibratedLength());
   }
   String options = Macro.getOptions();
   if (options != null && options.indexOf("straighten") != -1) p.fitSplineForStraightening();
   else if (options != null && options.indexOf("remove") != -1) p.removeSplineFit();
   else p.fitSpline();
   imp.draw();
   LineWidthAdjuster.update();
 }
Exemplo n.º 9
0
 void createEllipse(ImagePlus imp) {
   IJ.showStatus("Fitting ellipse");
   Roi roi = imp.getRoi();
   if (roi == null) {
     noRoi("Fit Ellipse");
     return;
   }
   if (roi.isLine()) {
     IJ.error("Fit Ellipse", "\"Fit Ellipse\" does not work with line selections");
     return;
   }
   ImageProcessor ip = imp.getProcessor();
   ip.setRoi(roi);
   int options = Measurements.CENTROID + Measurements.ELLIPSE;
   ImageStatistics stats = ImageStatistics.getStatistics(ip, options, null);
   double dx = stats.major * Math.cos(stats.angle / 180.0 * Math.PI) / 2.0;
   double dy = -stats.major * Math.sin(stats.angle / 180.0 * Math.PI) / 2.0;
   double x1 = stats.xCentroid - dx;
   double x2 = stats.xCentroid + dx;
   double y1 = stats.yCentroid - dy;
   double y2 = stats.yCentroid + dy;
   double aspectRatio = stats.minor / stats.major;
   imp.killRoi();
   imp.setRoi(new EllipseRoi(x1, y1, x2, y2, aspectRatio));
 }
Exemplo n.º 10
0
 boolean setProperties(String title, Roi roi) {
   Frame f = WindowManager.getFrontWindow();
   if (f != null && f.getTitle().indexOf("3D Viewer") != -1) return false;
   if (roi == null) {
     IJ.error("This command requires a selection.");
     return false;
   }
   RoiProperties rp = new RoiProperties(title, roi);
   return rp.showDialog();
 }
Exemplo n.º 11
0
 void areaToLine(ImagePlus imp) {
   Roi roi = imp.getRoi();
   if (roi == null || !roi.isArea()) {
     IJ.error("Area to Line", "Area selection required");
     return;
   }
   Polygon p = roi.getPolygon();
   if (p == null) return;
   int type1 = roi.getType();
   if (type1 == Roi.COMPOSITE) {
     IJ.error("Area to Line", "Composite selections cannot be converted to lines.");
     return;
   }
   int type2 = Roi.POLYLINE;
   if (type1 == Roi.OVAL
       || type1 == Roi.FREEROI
       || type1 == Roi.TRACED_ROI
       || ((roi instanceof PolygonRoi) && ((PolygonRoi) roi).isSplineFit())) type2 = Roi.FREELINE;
   Roi roi2 = new PolygonRoi(p.xpoints, p.ypoints, p.npoints, type2);
   imp.setRoi(roi2);
 }
Exemplo n.º 12
0
 void invert(ImagePlus imp) {
   Roi roi = imp.getRoi();
   if (roi == null || !roi.isArea()) {
     IJ.error("Inverse", "Area selection required");
     return;
   }
   ShapeRoi s1, s2;
   if (roi instanceof ShapeRoi) s1 = (ShapeRoi) roi;
   else s1 = new ShapeRoi(roi);
   s2 = new ShapeRoi(new Roi(0, 0, imp.getWidth(), imp.getHeight()));
   imp.setRoi(s1.xor(s2));
 }
Exemplo n.º 13
0
 void createMaskFromThreshold(ImagePlus imp) {
   ImageProcessor ip = imp.getProcessor();
   if (ip.getMinThreshold() == ImageProcessor.NO_THRESHOLD) {
     IJ.error("Create Mask", "Area selection or thresholded image required");
     return;
   }
   double t1 = ip.getMinThreshold();
   double t2 = ip.getMaxThreshold();
   IJ.run("Duplicate...", "title=mask");
   ImagePlus imp2 = WindowManager.getCurrentImage();
   ImageProcessor ip2 = imp2.getProcessor();
   ip2.setThreshold(t1, t2, ImageProcessor.NO_LUT_UPDATE);
   IJ.run("Convert to Mask");
 }
Exemplo n.º 14
0
 void convexHull(ImagePlus imp) {
   Roi roi = imp.getRoi();
   int type = roi != null ? roi.getType() : -1;
   if (!(type == Roi.FREEROI
       || type == Roi.TRACED_ROI
       || type == Roi.POLYGON
       || type == Roi.POINT)) {
     IJ.error("Convex Hull", "Polygonal or point selection required");
     return;
   }
   if (roi instanceof EllipseRoi) return;
   Polygon p = roi.getConvexHull();
   if (p != null) imp.setRoi(new PolygonRoi(p.xpoints, p.ypoints, p.npoints, roi.POLYGON));
 }
Exemplo n.º 15
0
 private RayFunction getRayFunction(int method, FloatProcessor fp) {
   switch (method) {
     case AVG_METHOD:
     case SUM_METHOD:
       return new AverageIntensity(fp, sliceCount);
     case MAX_METHOD:
       return new MaxIntensity(fp);
     case MIN_METHOD:
       return new MinIntensity(fp);
     case SD_METHOD:
       return new StandardDeviation(fp, sliceCount);
     default:
       IJ.error("Z Project", "Unknown method.");
       return null;
   }
 }
Exemplo n.º 16
0
 void lineToArea(ImagePlus imp) {
   Roi roi = imp.getRoi();
   if (roi == null || !roi.isLine()) {
     IJ.error("Line to Area", "Line selection required");
     return;
   }
   ImageProcessor ip2 = new ByteProcessor(imp.getWidth(), imp.getHeight());
   ip2.setColor(255);
   if (roi.getType() == Roi.LINE && roi.getStrokeWidth() > 1) ip2.fillPolygon(roi.getPolygon());
   else roi.drawPixels(ip2);
   // new ImagePlus("ip2", ip2.duplicate()).show();
   ip2.setThreshold(255, 255, ImageProcessor.NO_LUT_UPDATE);
   ThresholdToSelection tts = new ThresholdToSelection();
   Roi roi2 = tts.convert(ip2);
   imp.setRoi(roi2);
   Roi.previousRoi = (Roi) roi.clone();
 }
Exemplo n.º 17
0
 void createSelectionFromMask(ImagePlus imp) {
   ImageProcessor ip = imp.getProcessor();
   if (ip.getMinThreshold() != ImageProcessor.NO_THRESHOLD) {
     IJ.runPlugIn("ij.plugin.filter.ThresholdToSelection", "");
     return;
   }
   if (!ip.isBinary()) {
     IJ.error(
         "Create Selection",
         "This command creates a composite selection from\n"
             + "a mask (8-bit binary image with white background)\n"
             + "or from an image that has been thresholded using\n"
             + "the Image>Adjust>Threshold tool. The current\n"
             + "image is not a mask and has not been thresholded.");
     return;
   }
   int threshold = ip.isInvertedLut() ? 255 : 0;
   ip.setThreshold(threshold, threshold, ImageProcessor.NO_LUT_UPDATE);
   IJ.runPlugIn("ij.plugin.filter.ThresholdToSelection", "");
 }
Exemplo n.º 18
0
 void convexHull(ImagePlus imp) {
   Roi roi = imp.getRoi();
   int type = roi != null ? roi.getType() : -1;
   if (!(type == Roi.FREEROI
       || type == Roi.TRACED_ROI
       || type == Roi.POLYGON
       || type == Roi.POINT)) {
     IJ.error("Convex Hull", "Polygonal or point selection required");
     return;
   }
   if (roi instanceof EllipseRoi) return;
   // if (roi.subPixelResolution() && roi instanceof PolygonRoi) {
   //	FloatPolygon p = ((PolygonRoi)roi).getFloatConvexHull();
   //	if (p!=null)
   //		imp.setRoi(new PolygonRoi(p.xpoints, p.ypoints, p.npoints, roi.POLYGON));
   // } else {
   Polygon p = roi.getConvexHull();
   if (p != null) {
     Undo.setup(Undo.ROI, imp);
     Roi roi2 = new PolygonRoi(p.xpoints, p.ypoints, p.npoints, roi.POLYGON);
     transferProperties(roi, roi2);
     imp.setRoi(roi2);
   }
 }
Exemplo n.º 19
0
 private void makeBand(ImagePlus imp) {
   Roi roi = imp.getRoi();
   if (roi == null) {
     noRoi("Make Band");
     return;
   }
   if (!roi.isArea()) {
     IJ.error("Make Band", "Area selection required");
     return;
   }
   Calibration cal = imp.getCalibration();
   double pixels = bandSize;
   double size = pixels * cal.pixelWidth;
   int decimalPlaces = 0;
   if ((int) size != size) decimalPlaces = 2;
   GenericDialog gd = new GenericDialog("Make Band");
   gd.addNumericField("Band Size:", size, decimalPlaces, 4, cal.getUnits());
   gd.showDialog();
   if (gd.wasCanceled()) return;
   size = gd.getNextNumber();
   if (Double.isNaN(size)) {
     IJ.error("Make Band", "invalid number");
     return;
   }
   int n = (int) Math.round(size / cal.pixelWidth);
   if (n > 255) {
     IJ.error("Make Band", "Cannot make bands wider that 255 pixels");
     return;
   }
   int width = imp.getWidth();
   int height = imp.getHeight();
   Rectangle r = roi.getBounds();
   ImageProcessor ip = roi.getMask();
   if (ip == null) {
     ip = new ByteProcessor(r.width, r.height);
     ip.invert();
   }
   ImageProcessor mask = new ByteProcessor(width, height);
   mask.insert(ip, r.x, r.y);
   ImagePlus edm = new ImagePlus("mask", mask);
   boolean saveBlackBackground = Prefs.blackBackground;
   Prefs.blackBackground = false;
   IJ.run(edm, "Distance Map", "");
   Prefs.blackBackground = saveBlackBackground;
   ip = edm.getProcessor();
   ip.setThreshold(0, n, ImageProcessor.NO_LUT_UPDATE);
   int xx = -1, yy = -1;
   for (int x = r.x; x < r.x + r.width; x++) {
     for (int y = r.y; y < r.y + r.height; y++) {
       if (ip.getPixel(x, y) < n) {
         xx = x;
         yy = y;
         break;
       }
     }
     if (xx >= 0 || yy >= 0) break;
   }
   int count = IJ.doWand(edm, xx, yy, 0, null);
   if (count <= 0) {
     IJ.error("Make Band", "Unable to make band");
     return;
   }
   ShapeRoi roi2 = new ShapeRoi(edm.getRoi());
   if (!(roi instanceof ShapeRoi)) roi = new ShapeRoi(roi);
   ShapeRoi roi1 = (ShapeRoi) roi;
   roi2 = roi2.not(roi1);
   imp.setRoi(roi2);
   bandSize = n;
 }
Exemplo n.º 20
0
  public void run(String arg) {
    imp = IJ.getImage();
    int stackSize = imp.getStackSize();
    if (imp == null) {
      IJ.noImage();
      return;
    }

    //  Make sure input image is a stack.
    if (stackSize == 1) {
      IJ.error("Z Project", "Stack required");
      return;
    }

    //  Check for inverting LUT.
    if (imp.getProcessor().isInvertedLut()) {
      if (!IJ.showMessageWithCancel("ZProjection", lutMessage)) return;
    }

    // Set default bounds.
    int channels = imp.getNChannels();
    int frames = imp.getNFrames();
    int slices = imp.getNSlices();
    isHyperstack =
        imp.isHyperStack()
            || (ij.macro.Interpreter.isBatchMode()
                && ((frames > 1 && frames < stackSize) || (slices > 1 && slices < stackSize)));
    boolean simpleComposite = channels == stackSize;
    if (simpleComposite) isHyperstack = false;
    startSlice = 1;
    if (isHyperstack) {
      int nSlices = imp.getNSlices();
      if (nSlices > 1) stopSlice = nSlices;
      else stopSlice = imp.getNFrames();
    } else stopSlice = stackSize;

    // Build control dialog
    GenericDialog gd = buildControlDialog(startSlice, stopSlice);
    gd.showDialog();
    if (gd.wasCanceled()) return;

    if (!imp.lock()) return; // exit if in use
    long tstart = System.currentTimeMillis();
    setStartSlice((int) gd.getNextNumber());
    setStopSlice((int) gd.getNextNumber());
    method = gd.getNextChoiceIndex();
    Prefs.set(METHOD_KEY, method);
    if (isHyperstack) {
      allTimeFrames = imp.getNFrames() > 1 && imp.getNSlices() > 1 ? gd.getNextBoolean() : false;
      doHyperStackProjection(allTimeFrames);
    } else if (imp.getType() == ImagePlus.COLOR_RGB) doRGBProjection(true);
    else doProjection(true);

    if (arg.equals("") && projImage != null) {
      long tstop = System.currentTimeMillis();
      projImage.setCalibration(imp.getCalibration());
      if (simpleComposite) IJ.run(projImage, "Grays", "");
      projImage.show("ZProjector: " + IJ.d2s((tstop - tstart) / 1000.0, 2) + " seconds");
    }

    imp.unlock();
    IJ.register(ZProjector.class);
    return;
  }
  public void run(ImageProcessor ip) {
    String[] imageNames = getOpenImageNames();
    if (imageNames[0] == "None") {
      IJ.error("need at least 2 binary open images");
      return;
    }
    double previousMinOverlap = Prefs.get("BVTB.BinaryFeatureExtractor.minOverlap", 0);
    boolean previousCombine = Prefs.get("BVTB.BinaryFeatureExtractor.combine", false);

    GenericDialog gd = new GenericDialog("Binary Feature Extractor");
    gd.addChoice("Objects image", imageNames, imageNames[0]);
    gd.addChoice("Selector image", imageNames, imageNames[1]);
    gd.addNumericField("Object_overlap in % (0=off)", previousMinOverlap, 0, 9, "");
    gd.addCheckbox("Combine objects and selectors", previousCombine);
    gd.addCheckbox("Count output", true);
    gd.addCheckbox("Analysis tables", false);
    gd.showDialog();
    if (gd.wasCanceled()) {
      return;
    }
    String objectsImgTitle = gd.getNextChoice();
    String selectorsImgTitle = gd.getNextChoice();
    double minOverlap = gd.getNextNumber();
    boolean combineImages = gd.getNextBoolean();
    boolean showCountOutput = gd.getNextBoolean();
    boolean showAnalysis = gd.getNextBoolean();
    if (gd.invalidNumber() || minOverlap < 0 || minOverlap > 100) {
      IJ.error("invalid number");
      return;
    }
    Prefs.set("BVTB.BinaryFeatureExtractor.minOverlap", minOverlap);
    Prefs.set("BVTB.BinaryFeatureExtractor.combine", combineImages);

    if (objectsImgTitle.equals(selectorsImgTitle)) {
      IJ.error("images need to be different");
      return;
    }

    ImagePlus objectsImp = WindowManager.getImage(objectsImgTitle);
    ImageProcessor objectsIP = objectsImp.getProcessor();
    ImagePlus selectorsImp = WindowManager.getImage(selectorsImgTitle);
    ImageProcessor selectorsIP = selectorsImp.getProcessor();

    if (!objectsIP.isBinary() || !selectorsIP.isBinary()) {
      IJ.error("works with 8-bit binary images only");
      return;
    }

    if ((objectsImp.getWidth() != selectorsImp.getWidth())
        || objectsImp.getHeight() != selectorsImp.getHeight()) {
      IJ.error("images need to be of the same size");
      return;
    }

    // close any existing RoiManager before instantiating a new one for this analysis
    RoiManager oldRM = RoiManager.getInstance2();
    if (oldRM != null) {
      oldRM.close();
    }

    RoiManager objectsRM = new RoiManager(true);
    ResultsTable objectsRT = new ResultsTable();
    ParticleAnalyzer analyzeObjects =
        new ParticleAnalyzer(analyzerOptions, measurementFlags, objectsRT, 0.0, 999999999.9);
    analyzeObjects.setRoiManager(objectsRM);

    analyzeObjects.analyze(objectsImp);
    objectsRM.runCommand("Show None");
    int objectNumber = objectsRT.getCounter();

    Roi[] objectRoi = objectsRM.getRoisAsArray();

    ResultsTable measureSelectorsRT = new ResultsTable();
    Analyzer overlapAnalyzer = new Analyzer(selectorsImp, measurementFlags, measureSelectorsRT);

    ImagePlus outputImp =
        IJ.createImage("output", "8-bit black", objectsImp.getWidth(), objectsImp.getHeight(), 1);
    ImageProcessor outputIP = outputImp.getProcessor();

    double[] measuredOverlap = new double[objectNumber];

    outputIP.setValue(255.0);
    for (int o = 0; o < objectNumber; o++) {
      selectorsImp.killRoi();
      selectorsImp.setRoi(objectRoi[o]);
      overlapAnalyzer.measure();
      measuredOverlap[o] = measureSelectorsRT.getValue("%Area", o);
      if (minOverlap != 0.0 && measuredOverlap[o] >= minOverlap) {
        outputIP.fill(objectRoi[o]);
        finalCount++;
      } else if (minOverlap == 0.0 && measuredOverlap[o] > 0.0) {
        outputIP.fill(objectRoi[o]);
        finalCount++;
      }
    }
    // measureSelectorsRT.show("Objects");

    selectorsImp.killRoi();
    RoiManager selectorRM = new RoiManager(true);
    ResultsTable selectorRT = new ResultsTable();
    ParticleAnalyzer.setRoiManager(selectorRM);
    ParticleAnalyzer analyzeSelectors =
        new ParticleAnalyzer(analyzerOptions, measurementFlags, selectorRT, 0.0, 999999999.9);
    analyzeSelectors.analyze(selectorsImp);
    selectorRM.runCommand("Show None");
    int selectorNumber = selectorRT.getCounter();

    if (combineImages) {
      outputImp.updateAndDraw();
      Roi[] selectorRoi = selectorRM.getRoisAsArray();

      ResultsTable measureObjectsRT = new ResultsTable();
      Analyzer selectorAnalyzer = new Analyzer(outputImp, measurementFlags, measureObjectsRT);

      double[] selectorOverlap = new double[selectorNumber];
      outputIP.setValue(255.0);
      for (int s = 0; s < selectorNumber; s++) {
        outputImp.killRoi();
        outputImp.setRoi(selectorRoi[s]);
        selectorAnalyzer.measure();
        selectorOverlap[s] = measureObjectsRT.getValue("%Area", s);
        if (selectorOverlap[s] > 0.0d) {
          outputIP.fill(selectorRoi[s]);
        }
      }
      selectorRoi = null;
      selectorAnalyzer = null;
      measureObjectsRT = null;
    }
    // selectorRT.show("Selectors");
    outputImp.killRoi();
    String outputImageTitle = WindowManager.getUniqueName("Extracted_" + objectsImgTitle);
    outputImp.setTitle(outputImageTitle);
    outputImp.show();
    outputImp.changes = true;

    if (showCountOutput) {
      String[] openTextWindows = WindowManager.getNonImageTitles();
      boolean makeNewTable = true;
      for (int w = 0; w < openTextWindows.length; w++) {
        if (openTextWindows[w].equals("BFE_Results")) {
          makeNewTable = false;
        }
      }

      TextWindow existingCountTable = ResultsTable.getResultsWindow();
      if (makeNewTable) {
        countTable = new ResultsTable();
        countTable.setPrecision(0);
        countTable.setValue("Image", 0, outputImageTitle);
        countTable.setValue("Objects", 0, objectNumber);
        countTable.setValue("Selectors", 0, selectorNumber);
        countTable.setValue("Extracted", 0, finalCount);
        countTable.show("BFE_Results");
      } else {
        IJ.renameResults("BFE_Results", "Results");
        countTable = ResultsTable.getResultsTable();
        countTable.setPrecision(0);
        countTable.incrementCounter();
        countTable.addValue("Image", outputImageTitle);
        countTable.addValue("Objects", objectNumber);
        countTable.addValue("Selectors", selectorNumber);
        countTable.addValue("Extracted", finalCount);
        IJ.renameResults("Results", "BFE_Results");
        countTable.show("BFE_Results");
      }
    }

    if (showAnalysis) {
      ResultsTable extractedRT = new ResultsTable();
      ParticleAnalyzer analyzeExtracted =
          new ParticleAnalyzer(
              ParticleAnalyzer.CLEAR_WORKSHEET | ParticleAnalyzer.RECORD_STARTS,
              measurementFlags,
              extractedRT,
              0.0,
              999999999.9);
      analyzeExtracted.analyze(outputImp);
      objectsRT.show("Objects");
      selectorRT.show("Selectors");
      extractedRT.show("Extracted");
    } else {
      objectsRT = null;
      selectorRT = null;
    }

    objectsRM = null;
    measureSelectorsRT = null;
    analyzeObjects = null;
    overlapAnalyzer = null;
    objectRoi = null;
    selectorRM = null;

    objectsImp.killRoi();
    objectsImp.changes = false;
    selectorsImp.changes = false;
  }
Exemplo n.º 22
0
  /**
   * If 'applet' is not null, creates a new ImageJ frame that runs as an applet. If 'mode' is
   * ImageJ.EMBEDDED and 'applet is null, creates an embedded (non-standalone) version of ImageJ.
   */
  public ImageJ(java.applet.Applet applet, int mode) {
    super("ImageJ");
    if ((mode & DEBUG) != 0) IJ.setDebugMode(true);
    mode = mode & 255;
    if (IJ.debugMode) IJ.log("ImageJ starting in debug mode: " + mode);
    embedded = applet == null && (mode == EMBEDDED || mode == NO_SHOW);
    this.applet = applet;
    String err1 = Prefs.load(this, applet);
    setBackground(backgroundColor);
    Menus m = new Menus(this, applet);
    String err2 = m.addMenuBar();
    m.installPopupMenu(this);
    setLayout(new BorderLayout());

    // Tool bar
    toolbar = new Toolbar();
    toolbar.addKeyListener(this);
    add("Center", toolbar);

    // Status bar
    statusBar = new Panel();
    statusBar.setLayout(new BorderLayout());
    statusBar.setForeground(Color.black);
    statusBar.setBackground(backgroundColor);
    statusLine = new JLabel();
    statusLine.setFont(new Font("SansSerif", Font.PLAIN, 13));
    statusLine.addKeyListener(this);
    statusLine.addMouseListener(this);
    statusBar.add("Center", statusLine);
    progressBar = new ProgressBar(120, 20);
    progressBar.addKeyListener(this);
    progressBar.addMouseListener(this);
    statusBar.add("East", progressBar);
    add("South", statusBar);

    IJ.init(this, applet);
    addKeyListener(this);
    addWindowListener(this);
    setFocusTraversalKeysEnabled(false);
    m.installStartupMacroSet(); // add custom tools
    runStartupMacro();

    Point loc = getPreferredLocation();
    Dimension tbSize = toolbar.getPreferredSize();
    setCursor(Cursor.getDefaultCursor()); // work-around for JDK 1.1.8 bug
    if (mode != NO_SHOW) {
      if (IJ.isWindows())
        try {
          setIcon();
        } catch (Exception e) {
        }
      setLocation(loc.x, loc.y);
      setResizable(!IJ.isMacOSX());
      pack();
      setVisible(true);
    }
    if (err1 != null) IJ.error(err1);
    if (err2 != null) {
      IJ.error(err2);
      IJ.runPlugIn("ij.plugin.ClassChecker", "");
    }
    if (IJ.isMacintosh() && applet == null) {
      Object qh = null;
      qh = IJ.runPlugIn("MacAdapter", "");
      if (qh == null) IJ.runPlugIn("QuitHandler", "");
    }
    if (applet == null) IJ.runPlugIn("ij.plugin.DragAndDrop", "");
    String str = m.getMacroCount() == 1 ? " macro" : " macros";
    IJ.showStatus(version() + m.getPluginCount() + " commands; " + m.getMacroCount() + str);
    configureProxy();
    if (applet == null) loadCursors();
  }
Exemplo n.º 23
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();
    }
  }
Exemplo n.º 24
0
 void noRoi(String command) {
   IJ.error(command, "This command requires a selection");
 }
Exemplo n.º 25
0
  /*
  if selection is closed shape, create a circle with the same area and centroid, otherwise use<br>
  the Pratt method to fit a circle to the points that define the line or multi-point selection.<br>
  Reference: Pratt V., Direct least-squares fitting of algebraic surfaces", Computer Graphics, Vol. 21, pages 145-152 (1987).<br>
  Original code: Nikolai Chernov's MATLAB script for Newton-based Pratt fit.<br>
  (http://www.math.uab.edu/~chernov/cl/MATLABcircle.html)<br>
  Java version: https://github.com/mdoube/BoneJ/blob/master/src/org/doube/geometry/FitCircle.java<br>
  @authors Nikolai Chernov, Michael Doube, Ved Sharma
  */
  void fitCircle(ImagePlus imp) {
    Roi roi = imp.getRoi();
    if (roi == null) {
      noRoi("Fit Circle");
      return;
    }

    if (roi.isArea()) { // create circle with the same area and centroid
      ImageProcessor ip = imp.getProcessor();
      ip.setRoi(roi);
      ImageStatistics stats =
          ImageStatistics.getStatistics(ip, Measurements.AREA + Measurements.CENTROID, null);
      double r = Math.sqrt(stats.pixelCount / Math.PI);
      imp.killRoi();
      int d = (int) Math.round(2.0 * r);
      IJ.makeOval(
          (int) Math.round(stats.xCentroid - r), (int) Math.round(stats.yCentroid - r), d, d);
      return;
    }

    Polygon poly = roi.getPolygon();
    int n = poly.npoints;
    int[] x = poly.xpoints;
    int[] y = poly.ypoints;
    if (n < 3) {
      IJ.error("Fit Circle", "At least 3 points are required to fit a circle.");
      return;
    }

    // calculate point centroid
    double sumx = 0, sumy = 0;
    for (int i = 0; i < n; i++) {
      sumx = sumx + poly.xpoints[i];
      sumy = sumy + poly.ypoints[i];
    }
    double meanx = sumx / n;
    double meany = sumy / n;

    // calculate moments
    double[] X = new double[n], Y = new double[n];
    double Mxx = 0, Myy = 0, Mxy = 0, Mxz = 0, Myz = 0, Mzz = 0;
    for (int i = 0; i < n; i++) {
      X[i] = x[i] - meanx;
      Y[i] = y[i] - meany;
      double Zi = X[i] * X[i] + Y[i] * Y[i];
      Mxy = Mxy + X[i] * Y[i];
      Mxx = Mxx + X[i] * X[i];
      Myy = Myy + Y[i] * Y[i];
      Mxz = Mxz + X[i] * Zi;
      Myz = Myz + Y[i] * Zi;
      Mzz = Mzz + Zi * Zi;
    }
    Mxx = Mxx / n;
    Myy = Myy / n;
    Mxy = Mxy / n;
    Mxz = Mxz / n;
    Myz = Myz / n;
    Mzz = Mzz / n;

    // calculate the coefficients of the characteristic polynomial
    double Mz = Mxx + Myy;
    double Cov_xy = Mxx * Myy - Mxy * Mxy;
    double Mxz2 = Mxz * Mxz;
    double Myz2 = Myz * Myz;
    double A2 = 4 * Cov_xy - 3 * Mz * Mz - Mzz;
    double A1 = Mzz * Mz + 4 * Cov_xy * Mz - Mxz2 - Myz2 - Mz * Mz * Mz;
    double A0 = Mxz2 * Myy + Myz2 * Mxx - Mzz * Cov_xy - 2 * Mxz * Myz * Mxy + Mz * Mz * Cov_xy;
    double A22 = A2 + A2;
    double epsilon = 1e-12;
    double ynew = 1e+20;
    int IterMax = 20;
    double xnew = 0;
    int iterations = 0;

    // Newton's method starting at x=0
    for (int iter = 1; iter <= IterMax; iter++) {
      iterations = iter;
      double yold = ynew;
      ynew = A0 + xnew * (A1 + xnew * (A2 + 4. * xnew * xnew));
      if (Math.abs(ynew) > Math.abs(yold)) {
        if (IJ.debugMode) IJ.log("Fit Circle: wrong direction: |ynew| > |yold|");
        xnew = 0;
        break;
      }
      double Dy = A1 + xnew * (A22 + 16 * xnew * xnew);
      double xold = xnew;
      xnew = xold - ynew / Dy;
      if (Math.abs((xnew - xold) / xnew) < epsilon) break;
      if (iter >= IterMax) {
        if (IJ.debugMode) IJ.log("Fit Circle: will not converge");
        xnew = 0;
      }
      if (xnew < 0) {
        if (IJ.debugMode) IJ.log("Fit Circle: negative root:  x = " + xnew);
        xnew = 0;
      }
    }
    if (IJ.debugMode)
      IJ.log("Fit Circle: n=" + n + ", xnew=" + IJ.d2s(xnew, 2) + ", iterations=" + iterations);

    // calculate the circle parameters
    double DET = xnew * xnew - xnew * Mz + Cov_xy;
    double CenterX = (Mxz * (Myy - xnew) - Myz * Mxy) / (2 * DET);
    double CenterY = (Myz * (Mxx - xnew) - Mxz * Mxy) / (2 * DET);
    double radius = Math.sqrt(CenterX * CenterX + CenterY * CenterY + Mz + 2 * xnew);
    if (Double.isNaN(radius)) {
      IJ.error("Fit Circle", "Points are collinear.");
      return;
    }
    CenterX = CenterX + meanx;
    CenterY = CenterY + meany;
    imp.killRoi();
    IJ.makeOval(
        (int) Math.round(CenterX - radius),
        (int) Math.round(CenterY - radius),
        (int) Math.round(2 * radius),
        (int) Math.round(2 * radius));
  }
Exemplo n.º 26
0
  /**
   * If 'applet' is not null, creates a new ImageJ frame that runs as an applet. If 'mode' is
   * ImageJ.EMBEDDED and 'applet is null, creates an embedded (non-standalone) version of ImageJ.
   */
  public ImageJ(java.applet.Applet applet, int mode) {
    super("ImageJ");
    embedded = applet == null && (mode == EMBEDDED || mode == NO_SHOW);
    this.applet = applet;
    String err1 = Prefs.load(this, applet);
    if (IJ.isLinux()) {
      backgroundColor = new Color(240, 240, 240);
      setBackground(backgroundColor);
    }
    Menus m = new Menus(this, applet);
    String err2 = m.addMenuBar();
    m.installPopupMenu(this);
    setLayout(new GridLayout(2, 1));

    // Tool bar
    toolbar = new Toolbar();
    toolbar.addKeyListener(this);
    add(toolbar);

    // Status bar
    statusBar = new Panel();
    statusBar.setLayout(new BorderLayout());
    statusBar.setForeground(Color.black);
    statusBar.setBackground(backgroundColor);
    statusLine = new Label();
    statusLine.setFont(SansSerif12);
    statusLine.addKeyListener(this);
    statusLine.addMouseListener(this);
    statusBar.add("Center", statusLine);
    progressBar = new ProgressBar(120, 20);
    progressBar.addKeyListener(this);
    progressBar.addMouseListener(this);
    statusBar.add("East", progressBar);
    statusBar.setSize(toolbar.getPreferredSize());
    add(statusBar);

    IJ.init(this, applet);
    addKeyListener(this);
    addWindowListener(this);
    setFocusTraversalKeysEnabled(false);

    Point loc = getPreferredLocation();
    Dimension tbSize = toolbar.getPreferredSize();
    int ijWidth = tbSize.width + 10;
    int ijHeight = 100;
    setCursor(Cursor.getDefaultCursor()); // work-around for JDK 1.1.8 bug
    if (mode != NO_SHOW) {
      if (IJ.isWindows())
        try {
          setIcon();
        } catch (Exception e) {
        }
      setBounds(loc.x, loc.y, ijWidth, ijHeight); // needed for pack to work
      setLocation(loc.x, loc.y);
      pack();
      setResizable(!(IJ.isMacintosh() || IJ.isWindows())); // make resizable on Linux
      show();
    }
    if (err1 != null) IJ.error(err1);
    if (err2 != null) {
      IJ.error(err2);
      IJ.runPlugIn("ij.plugin.ClassChecker", "");
    }
    m.installStartupMacroSet();
    if (IJ.isMacintosh() && applet == null) {
      Object qh = null;
      qh = IJ.runPlugIn("MacAdapter", "");
      if (qh == null) IJ.runPlugIn("QuitHandler", "");
    }
    if (applet == null) IJ.runPlugIn("ij.plugin.DragAndDrop", "");
    String str = m.getMacroCount() == 1 ? " macro" : " macros";
    IJ.showStatus(version() + m.getPluginCount() + " commands; " + m.getMacroCount() + str);
    // if (applet==null && !embedded && Prefs.runSocketListener)
    //	new SocketListener();
    configureProxy();
    if (applet == null) loadCursors();
  }