Ejemplo n.º 1
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) {
     FloatPolygon p = roi.getFloatPolygon();
     roi2 = new PolygonRoi(p, Roi.POLYGON);
   } 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();
 }
Ejemplo n.º 2
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));
 }
Ejemplo n.º 3
0
 void createMask(ImagePlus imp) {
   Roi roi = imp.getRoi();
   boolean useInvertingLut = Prefs.useInvertingLut;
   Prefs.useInvertingLut = false;
   if (roi == null || !(roi.isArea() || roi.getType() == Roi.POINT)) {
     createMaskFromThreshold(imp);
     Prefs.useInvertingLut = useInvertingLut;
     return;
   }
   ImagePlus maskImp = null;
   Frame frame = WindowManager.getFrame("Mask");
   if (frame != null && (frame instanceof ImageWindow))
     maskImp = ((ImageWindow) frame).getImagePlus();
   if (maskImp == null) {
     ImageProcessor ip = new ByteProcessor(imp.getWidth(), imp.getHeight());
     if (!Prefs.blackBackground) ip.invertLut();
     maskImp = new ImagePlus("Mask", ip);
     maskImp.show();
   }
   ImageProcessor ip = maskImp.getProcessor();
   ip.setRoi(roi);
   ip.setValue(255);
   ip.fill(ip.getMask());
   maskImp.updateAndDraw();
   Prefs.useInvertingLut = useInvertingLut;
 }
Ejemplo n.º 4
0
 void runMacro(String arg) {
   Roi roi = imp.getRoi();
   if (IJ.macroRunning()) {
     String options = Macro.getOptions();
     if (options != null
         && (options.indexOf("grid=") != -1 || options.indexOf("interpolat") != -1)) {
       IJ.run("Rotate... ", options); // run Image>Transform>Rotate
       return;
     }
   }
   if (roi == null) {
     noRoi("Rotate>Selection");
     return;
   }
   roi = (Roi) roi.clone();
   if (arg.equals("rotate")) {
     double d = Tools.parseDouble(angle);
     if (Double.isNaN(d)) angle = "15";
     String value = IJ.runMacroFile("ij.jar:RotateSelection", angle);
     if (value != null) angle = value;
   } else if (arg.equals("enlarge")) {
     String value = IJ.runMacroFile("ij.jar:EnlargeSelection", enlarge);
     if (value != null) enlarge = value;
     Roi.previousRoi = roi;
   }
 }
Ejemplo n.º 5
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);
 }
Ejemplo n.º 6
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();
 }
Ejemplo n.º 7
0
 private void enlarge(ImagePlus imp) {
   Roi roi = imp.getRoi();
   if (roi != null) {
     Undo.setup(Undo.ROI, imp);
     roi = (Roi) roi.clone();
     (new RoiEnlarger()).run("");
   } else noRoi("Enlarge");
 }
Ejemplo n.º 8
0
 void toBoundingBox(ImagePlus imp) {
   Roi roi = imp.getRoi();
   if (roi == null) {
     noRoi("To Bounding Box");
     return;
   }
   Rectangle r = roi.getBounds();
   imp.killRoi();
   imp.setRoi(new Roi(r.x, r.y, r.width, r.height));
 }
Ejemplo n.º 9
0
 // Added by Marcel Boeglin 2013.09.22
 private Overlay projectHyperStackRois(Overlay overlay) {
   if (overlay == null) return null;
   int t1 = imp.getFrame();
   int channels = projImage.getNChannels();
   int slices = 1;
   int frames = projImage.getNFrames();
   Overlay overlay2 = new Overlay();
   Roi roi;
   int c, z, t;
   int size = channels * slices * frames;
   for (Roi r : overlay.toArray()) {
     c = r.getCPosition();
     z = r.getZPosition();
     t = r.getTPosition();
     roi = (Roi) r.clone();
     if (size == channels) { // current time frame
       if (z >= startSlice && z <= stopSlice && t == t1 || c == 0) {
         roi.setPosition(c);
         overlay2.add(roi);
       }
     } else if (size == frames * channels) { // all time frames
       if (z >= startSlice && z <= stopSlice) roi.setPosition(c, 1, t);
       else if (z == 0) roi.setPosition(c, 0, t);
       else continue;
       overlay2.add(roi);
     }
   }
   return overlay2;
 }
Ejemplo n.º 10
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));
 }
Ejemplo n.º 11
0
 void toBoundingBox(ImagePlus imp) {
   Roi roi = imp.getRoi();
   if (roi == null) {
     noRoi("To Bounding Box");
     return;
   }
   Undo.setup(Undo.ROI, imp);
   Rectangle r = roi.getBounds();
   imp.deleteRoi();
   Roi roi2 = new Roi(r.x, r.y, r.width, r.height);
   transferProperties(roi, roi2);
   imp.setRoi(roi2);
 }
Ejemplo n.º 12
0
 void lineWidth() {
   int width = (int) IJ.getNumber("Line Width:", Line.getWidth());
   if (width == IJ.CANCELED) return;
   Line.setWidth(width);
   LineWidthAdjuster.update();
   ImagePlus imp = WindowManager.getCurrentImage();
   if (imp != null && imp.isProcessor()) {
     ImageProcessor ip = imp.getProcessor();
     ip.setLineWidth(Line.getWidth());
     Roi roi = imp.getRoi();
     if (roi != null && roi.isLine()) imp.draw();
   }
 }
Ejemplo n.º 13
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));
 }
Ejemplo n.º 14
0
 // Added by Marcel Boeglin 2013.09.23
 private Overlay projectStackRois(Overlay overlay) {
   if (overlay == null) return null;
   Overlay overlay2 = new Overlay();
   Roi roi;
   int s;
   for (Roi r : overlay.toArray()) {
     s = r.getPosition();
     roi = (Roi) r.clone();
     if (s >= startSlice && s <= stopSlice || s == 0) {
       roi.setPosition(s);
       overlay2.add(roi);
     }
   }
   return overlay2;
 }
Ejemplo n.º 15
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);
 }
Ejemplo n.º 16
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);
   boolean ok = rp.showDialog();
   if (IJ.debugMode) IJ.log(roi.getDebugInfo());
   return ok;
 }
Ejemplo n.º 17
0
 void createMask(ImagePlus imp) {
   Roi roi = imp.getRoi();
   boolean useInvertingLut = Prefs.useInvertingLut;
   Prefs.useInvertingLut = false;
   boolean selectAll =
       roi != null
           && roi.getType() == Roi.RECTANGLE
           && roi.getBounds().width == imp.getWidth()
           && roi.getBounds().height == imp.getHeight()
           && imp.isThreshold();
   if (roi == null || !(roi.isArea() || roi.getType() == Roi.POINT) || selectAll) {
     createMaskFromThreshold(imp);
     Prefs.useInvertingLut = useInvertingLut;
     return;
   }
   ImagePlus maskImp = null;
   Frame frame = WindowManager.getFrame("Mask");
   if (frame != null && (frame instanceof ImageWindow))
     maskImp = ((ImageWindow) frame).getImagePlus();
   if (maskImp == null) {
     ImageProcessor ip = new ByteProcessor(imp.getWidth(), imp.getHeight());
     if (!Prefs.blackBackground) ip.invertLut();
     maskImp = new ImagePlus("Mask", ip);
     maskImp.show();
   }
   ImageProcessor ip = maskImp.getProcessor();
   ip.setRoi(roi);
   ip.setValue(255);
   ip.fill(ip.getMask());
   Calibration cal = imp.getCalibration();
   if (cal.scaled()) {
     Calibration cal2 = maskImp.getCalibration();
     cal2.pixelWidth = cal.pixelWidth;
     cal2.pixelHeight = cal.pixelHeight;
     cal2.setUnit(cal.getUnit());
   }
   maskImp.updateAndRepaintWindow();
   Prefs.useInvertingLut = useInvertingLut;
 }
Ejemplo n.º 18
0
 void runMacro(String arg, ImagePlus imp) {
   boolean rotate = arg.equals("rotate");
   Roi roi = imp.getRoi();
   if (rotate && IJ.macroRunning()) {
     String options = Macro.getOptions();
     if (options != null
         && (options.indexOf("grid=") != -1 || options.indexOf("interpolat") != -1)) {
       IJ.run("Rotate... ", options); // run Image>Transform>Rotate
       return;
     }
   }
   if (roi == null) {
     noRoi(rotate ? "Rotate" : "Enlarge");
     return;
   }
   double dangle = Tools.parseDouble(angle);
   if (Double.isNaN(dangle)) {
     dangle = 15;
     angle = "" + dangle;
   }
   if (rotate && (roi instanceof ImageRoi)) {
     dangle = IJ.getNumber("Angle (degrees):", dangle);
     ((ImageRoi) roi).rotate(dangle);
     imp.draw();
     angle = "" + dangle;
     return;
   }
   Undo.setup(Undo.ROI, imp);
   roi = (Roi) roi.clone();
   if (rotate) {
     String value = IJ.runMacroFile("ij.jar:RotateSelection", angle);
     Roi roi2 = imp.getRoi();
     transferProperties(roi, roi2);
     imp.setRoi(roi2);
     if (value != null) angle = value;
   } else if (arg.equals("enlarge")) (new RoiEnlarger()).run("");
 }
Ejemplo n.º 19
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);
   }
 }
Ejemplo n.º 20
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();
 }
Ejemplo n.º 21
0
 // Added by Marcel Boeglin 2013.09.22
 private Overlay projectRGBHyperStackRois(Overlay overlay) {
   if (overlay == null) return null;
   int frames = projImage.getNFrames();
   int t1 = imp.getFrame();
   Overlay overlay2 = new Overlay();
   Roi roi;
   int c, z, t;
   for (Roi r : overlay.toArray()) {
     c = r.getCPosition();
     z = r.getZPosition();
     t = r.getTPosition();
     roi = (Roi) r.clone();
     if (z >= startSlice && z <= stopSlice || z == 0 || c == 0 || t == 0) {
       if (frames == 1 && t != t1 && t != 0) // current time frame
       continue;
       roi.setPosition(t);
       overlay2.add(roi);
     }
   }
   return overlay2;
 }
Ejemplo n.º 22
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));
  }
Ejemplo n.º 23
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;
 }
Ejemplo n.º 24
0
  void Otsu(ImagePlus imp, int radius, double par1, double par2, boolean doIwhite) {
    // Otsu's threshold algorithm
    // C++ code by Jordan Bevik <*****@*****.**>
    // ported to ImageJ plugin by G.Landini. Same algorithm as in Auto_Threshold, this time on local
    // circular regions
    int[] data;
    int w = imp.getWidth();
    int h = imp.getHeight();
    int position;
    int radiusx2 = radius * 2;
    ImageProcessor ip = imp.getProcessor();
    byte[] pixels = (byte[]) ip.getPixels();
    byte[] pixelsOut =
        new byte
            [pixels.length]; // need this to avoid changing the image data (and further histograms)
    byte object;
    byte backg;

    if (doIwhite) {
      object = (byte) 0xff;
      backg = (byte) 0;
    } else {
      object = (byte) 0;
      backg = (byte) 0xff;
    }

    int k, kStar; // k = the current threshold; kStar = optimal threshold
    int N1, N; // N1 = # points with intensity <=k; N = total number of points
    double BCV, BCVmax; // The current Between Class Variance and maximum BCV
    double num, denom; // temporary bookeeping
    int Sk; // The total intensity for all histogram points <=k
    int S,
        L =
            256; // The total intensity of the image. Need to hange here if modifying for >8 bits
                 // images
    int roiy;

    Roi roi = new OvalRoi(0, 0, radiusx2, radiusx2);
    // ip.setRoi(roi);
    for (int y = 0; y < h; y++) {
      IJ.showProgress(
          (double) (y) / (h - 1)); // this method is slow, so let's show the progress bar
      roiy = y - radius;
      for (int x = 0; x < w; x++) {
        roi.setLocation(x - radius, roiy);
        ip.setRoi(roi);
        // ip.setRoi(new OvalRoi(x-radius, roiy, radiusx2, radiusx2));
        position = x + y * w;
        data = ip.getHistogram();

        // Initialize values:
        S = N = 0;
        for (k = 0; k < L; k++) {
          S += k * data[k]; // Total histogram intensity
          N += data[k]; // Total number of data points
        }

        Sk = 0;
        N1 = data[0]; // The entry for zero intensity
        BCV = 0;
        BCVmax = 0;
        kStar = 0;

        // Look at each possible threshold value,
        // calculate the between-class variance, and decide if it's a max
        for (k = 1; k < L - 1; k++) { // No need to check endpoints k = 0 or k = L-1
          Sk += k * data[k];
          N1 += data[k];

          // The float casting here is to avoid compiler warning about loss of precision and
          // will prevent overflow in the case of large saturated images
          denom = (double) (N1) * (N - N1); // Maximum value of denom is (N^2)/4 =  approx. 3E10

          if (denom != 0) {
            // Float here is to avoid loss of precision when dividing
            num = ((double) N1 / N) * S - Sk; // Maximum value of num =  255*N = approx 8E7
            BCV = (num * num) / denom;
          } else BCV = 0;

          if (BCV >= BCVmax) { // Assign the best threshold found so far
            BCVmax = BCV;
            kStar = k;
          }
        }
        // kStar += 1;	// Use QTI convention that intensity -> 1 if intensity >= k
        // (the algorithm was developed for I-> 1 if I <= k.)
        // return kStar;
        pixelsOut[position] = ((int) (pixels[position] & 0xff) > kStar) ? object : backg;
      }
    }
    for (position = 0; position < w * h; position++)
      pixels[position] = pixelsOut[position]; // update with thresholded pixels
  }
Ejemplo n.º 25
0
 void interpolate() {
   Roi roi = imp.getRoi();
   if (roi == null) {
     noRoi("Interpolate");
     return;
   }
   if (roi.getType() == Roi.POINT) return;
   if (IJ.isMacro() && Macro.getOptions() == null) Macro.setOptions("interval=1");
   GenericDialog gd = new GenericDialog("Interpolate");
   gd.addNumericField("Interval:", 1.0, 1, 4, "pixel");
   gd.addCheckbox("Smooth", IJ.isMacro() ? false : smooth);
   gd.addCheckbox("Adjust interval to match", IJ.isMacro() ? false : adjust);
   gd.showDialog();
   if (gd.wasCanceled()) return;
   double interval = gd.getNextNumber();
   smooth = gd.getNextBoolean();
   Undo.setup(Undo.ROI, imp);
   adjust = gd.getNextBoolean();
   int sign = adjust ? -1 : 1;
   FloatPolygon poly = roi.getInterpolatedPolygon(sign * interval, smooth);
   int t = roi.getType();
   int type = roi.isLine() ? Roi.FREELINE : Roi.FREEROI;
   if (t == Roi.POLYGON && interval > 1.0) type = Roi.POLYGON;
   if ((t == Roi.RECTANGLE || t == Roi.OVAL || t == Roi.FREEROI) && interval >= 8.0)
     type = Roi.POLYGON;
   if ((t == Roi.LINE || t == Roi.FREELINE) && interval >= 8.0) type = Roi.POLYLINE;
   if (t == Roi.POLYLINE && interval >= 8.0) type = Roi.POLYLINE;
   ImageCanvas ic = imp.getCanvas();
   if (poly.npoints <= 150 && ic != null && ic.getMagnification() >= 12.0)
     type = roi.isLine() ? Roi.POLYLINE : Roi.POLYGON;
   Roi p = new PolygonRoi(poly, type);
   if (roi.getStroke() != null) p.setStrokeWidth(roi.getStrokeWidth());
   p.setStrokeColor(roi.getStrokeColor());
   p.setName(roi.getName());
   transferProperties(roi, p);
   imp.setRoi(p);
 }
Ejemplo n.º 26
0
 private void transferProperties(Roi roi1, Roi roi2) {
   if (roi1 == null || roi2 == null) return;
   roi2.setStrokeColor(roi1.getStrokeColor());
   if (roi1.getStroke() != null) roi2.setStroke(roi1.getStroke());
   roi2.setDrawOffset(roi1.getDrawOffset());
 }
Ejemplo n.º 27
0
  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;
      }
    }
  }