Example #1
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.showDialog();
   if (gd.wasCanceled()) return;
   double interval = gd.getNextNumber();
   smooth = gd.getNextBoolean();
   Undo.setup(Undo.ROI, imp);
   FloatPolygon poly = roi.getInterpolatedPolygon(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 >= 5.0)
     type = Roi.POLYGON;
   if ((t == Roi.LINE || t == Roi.FREELINE) && interval >= 5.0) type = Roi.POLYLINE;
   if (t == Roi.POLYLINE && interval >= 1.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);
 }
 public void mouseMoved(MouseEvent e) {
   // if (ij==null) return;
   int sx = e.getX();
   int sy = e.getY();
   int ox = offScreenX(sx);
   int oy = offScreenY(sy);
   flags = e.getModifiers();
   setCursor(sx, sy, ox, oy);
   IJ.setInputEvent(e);
   Roi roi = imp.getRoi();
   if (roi != null
       && (roi.getType() == Roi.POLYGON
           || roi.getType() == Roi.POLYLINE
           || roi.getType() == Roi.ANGLE)
       && roi.getState() == roi.CONSTRUCTING) {
     PolygonRoi pRoi = (PolygonRoi) roi;
     pRoi.handleMouseMove(ox, oy);
   } else {
     if (ox < imageWidth && oy < imageHeight) {
       ImageWindow win = imp.getWindow();
       // Cursor must move at least 12 pixels before text
       // displayed using IJ.showStatus() is overwritten.
       if ((sx - sx2) * (sx - sx2) + (sy - sy2) * (sy - sy2) > 144) showCursorStatus = true;
       if (win != null && showCursorStatus) win.mouseMoved(ox, oy);
     } else IJ.showStatus("");
   }
 }
Example #3
0
  /*------------------------------------------------------------------*/
  void setupProgressBar() {
    int height = imp.getHeight();
    int width = imp.getWidth();

    completed = 0;
    lastTime = System.currentTimeMillis();
    switch (operation) {
      case GRADIENT_MAGNITUDE:
        processDuration = stackSize * (width + 2 * height);
        break;
      case GRADIENT_DIRECTION:
        processDuration = stackSize * (width + 2 * height);
        break;
      case LAPLACIAN:
        processDuration = stackSize * (width + 2 * height);
        break;
      case LARGEST_HESSIAN:
        processDuration = stackSize * (2 * width + 3 * height);
        break;
      case SMALLEST_HESSIAN:
        processDuration = stackSize * (2 * width + 3 * height);
        break;
      case HESSIAN_ORIENTATION:
        processDuration = stackSize * (2 * width + 3 * height);
        break;
      default:
        throw new IllegalArgumentException("Invalid operation");
    }
  } /* end setupProgressBar */
Example #4
0
 void lineToArea(ImagePlus imp) {
   Roi roi = imp.getRoi();
   if (roi == null || !roi.isLine()) {
     IJ.error("Line to Area", "Line selection required");
     return;
   }
   if (roi.getType() == Roi.LINE && roi.getStrokeWidth() == 1) {
     IJ.error("Line to Area", "Straight line width must be > 1");
     return;
   }
   ImageProcessor ip2 = new ByteProcessor(imp.getWidth(), imp.getHeight());
   ip2.setColor(255);
   if (roi.getType() == Roi.LINE) ip2.fillPolygon(roi.getPolygon());
   else {
     roi.drawPixels(ip2);
     // BufferedImage bi = new BufferedImage(imp.getWidth(), imp.getHeight(),
     // BufferedImage.TYPE_BYTE_GRAY);
     // Graphics g = bi.getGraphics();
     // Roi roi2 = (Roi)roi.clone();
     // roi2.setStrokeColor(Color.white);
     // roi2.drawOverlay(g);
     // ip2 = new ByteProcessor(bi);
   }
   // 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();
 }
Example #5
0
  /** Generate output image whose type is same as input image. */
  private ImagePlus makeOutputImage(ImagePlus imp, FloatProcessor fp, int ptype) {
    int width = imp.getWidth();
    int height = imp.getHeight();
    float[] pixels = (float[]) fp.getPixels();
    ImageProcessor oip = null;

    // Create output image consistent w/ type of input image.
    int size = pixels.length;
    switch (ptype) {
      case BYTE_TYPE:
        oip = imp.getProcessor().createProcessor(width, height);
        byte[] pixels8 = (byte[]) oip.getPixels();
        for (int i = 0; i < size; i++) pixels8[i] = (byte) pixels[i];
        break;
      case SHORT_TYPE:
        oip = imp.getProcessor().createProcessor(width, height);
        short[] pixels16 = (short[]) oip.getPixels();
        for (int i = 0; i < size; i++) pixels16[i] = (short) pixels[i];
        break;
      case FLOAT_TYPE:
        oip = new FloatProcessor(width, height, pixels, null);
        break;
    }

    // Adjust for display.
    // Calling this on non-ByteProcessors ensures image
    // processor is set up to correctly display image.
    oip.resetMinAndMax();

    // Create new image plus object. Don't use
    // ImagePlus.createImagePlus here because there may be
    // attributes of input image that are not appropriate for
    // projection.
    return new ImagePlus(makeTitle(), oip);
  }
 /** Sets the cursor based on the current tool and cursor location. */
 public void setCursor(int sx, int sy, int ox, int oy) {
   xMouse = ox;
   yMouse = oy;
   mouseExited = false;
   Roi roi = imp.getRoi();
   ImageWindow win = imp.getWindow();
   if (win == null) return;
   if (IJ.spaceBarDown()) {
     setCursor(handCursor);
     return;
   }
   int id = Toolbar.getToolId();
   switch (Toolbar.getToolId()) {
     case Toolbar.MAGNIFIER:
       setCursor(moveCursor);
       break;
     case Toolbar.HAND:
       setCursor(handCursor);
       break;
     default: // selection tool
       if (id == Toolbar.SPARE1 || id >= Toolbar.SPARE2) {
         if (Prefs.usePointerCursor) setCursor(defaultCursor);
         else setCursor(crosshairCursor);
       } else if (roi != null && roi.getState() != roi.CONSTRUCTING && roi.isHandle(sx, sy) >= 0)
         setCursor(handCursor);
       else if (Prefs.usePointerCursor
           || (roi != null && roi.getState() != roi.CONSTRUCTING && roi.contains(ox, oy)))
         setCursor(defaultCursor);
       else setCursor(crosshairCursor);
   }
 }
Example #7
0
  /**
   * Prepare for processing; also called at the very end with argument 'final' to show any newly
   * created output image.
   */
  public int setup(String arg, ImagePlus imp) {
    if (arg.equals("final")) {
      showOutput();
      return DONE;
    }
    this.imp = imp;
    // 'arg' is processing type; default is 'EDM' (0)
    if (arg.equals("watershed")) {
      processType = WATERSHED;
      flags += KEEP_THRESHOLD;
    } else if (arg.equals("points")) processType = UEP;
    else if (arg.equals("voronoi")) processType = VORONOI;

    // output type
    if (processType != WATERSHED) // Watershed always has output BYTE_OVERWRITE=0
    outImageType = outputType; // otherwise use the static variable from setOutputType
    if (outImageType != BYTE_OVERWRITE) flags |= NO_CHANGES;

    // check image and prepare
    if (imp != null) {
      ImageProcessor ip = imp.getProcessor();
      if (!ip.isBinary()) {
        IJ.error("8-bit binary image (0 and 255) required.");
        return DONE;
      }
      ip.resetRoi();
      // processing routines assume background=0; image may be otherwise
      boolean invertedLut = imp.isInvertedLut();
      background255 =
          (invertedLut && Prefs.blackBackground) || (!invertedLut && !Prefs.blackBackground);
    }
    return flags;
  } // public int setup
Example #8
0
 void showDialog() {
   int width = imp.getWidth();
   int height = imp.getHeight();
   Calibration cal = imp.getCalibration();
   int places;
   if (cal.scaled()) {
     pixelWidth = cal.pixelWidth;
     pixelHeight = cal.pixelHeight;
     units = cal.getUnits();
     places = 2;
   } else {
     pixelWidth = 1.0;
     pixelHeight = 1.0;
     units = "pixels";
     places = 0;
   }
   if (areaPerPoint == 0.0)
     areaPerPoint =
         (width * cal.pixelWidth * height * cal.pixelHeight) / 81.0; // default to 9x9 grid
   ImageWindow win = imp.getWindow();
   GenericDialog gd = new GenericDialog("Grid...");
   gd.addChoice("Grid Type:", types, type);
   gd.addNumericField("Area per Point:", areaPerPoint, places, 6, units + "^2");
   gd.addChoice("Color:", colors, color);
   gd.addCheckbox("Random Offset", randomOffset);
   gd.addDialogListener(this);
   gd.showDialog();
   if (gd.wasCanceled()) showGrid(null);
 }
Example #9
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();
 }
Example #10
0
 void remove() {
   ImagePlus imp = WindowManager.getCurrentImage();
   if (imp != null) imp.setOverlay(null);
   overlay2 = null;
   RoiManager rm = RoiManager.getInstance();
   if (rm != null) rm.runCommand("show none");
 }
 /**
  * Saves statistics for one particle in a results table. This is a method subclasses may want to
  * override.
  */
 protected void saveResults(ImageStatistics stats, Roi roi) {
   analyzer.saveResults(stats, roi);
   if (recordStarts) {
     rt.addValue("XStart", stats.xstart);
     rt.addValue("YStart", stats.ystart);
   }
   if (addToManager) {
     if (roiManager == null) {
       if (Macro.getOptions() != null && Interpreter.isBatchMode())
         roiManager = Interpreter.getBatchModeRoiManager();
       if (roiManager == null) {
         Frame frame = WindowManager.getFrame("ROI Manager");
         if (frame == null) IJ.run("ROI Manager...");
         frame = WindowManager.getFrame("ROI Manager");
         if (frame == null || !(frame instanceof RoiManager)) {
           addToManager = false;
           return;
         }
         roiManager = (RoiManager) frame;
       }
       if (resetCounter) roiManager.runCommand("reset");
     }
     if (imp.getStackSize() > 1) roi.setPosition(imp.getCurrentSlice());
     if (lineWidth != 1) roi.setStrokeWidth(lineWidth);
     roiManager.add(imp, roi, rt.getCounter());
   }
   if (showResults) rt.addResults();
 }
Example #12
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;
 }
 public int setup(String arg, ImagePlus imp) {
   this.arg = arg;
   this.imp = imp;
   IJ.register(ParticleAnalyzer.class);
   if (imp == null) {
     IJ.noImage();
     return DONE;
   }
   if (imp.getBitDepth() == 24 && !isThresholdedRGB(imp)) {
     IJ.error(
         "Particle Analyzer",
         "RGB images must be thresholded using\n" + "Image>Adjust>Color Threshold.");
     return DONE;
   }
   if (!showDialog()) return DONE;
   int baseFlags = DOES_ALL + NO_CHANGES + NO_UNDO;
   int flags = IJ.setupDialog(imp, baseFlags);
   processStack = (flags & DOES_STACKS) != 0;
   slice = 0;
   saveRoi = imp.getRoi();
   if (saveRoi != null && saveRoi.getType() != Roi.RECTANGLE && saveRoi.isArea())
     polygon = saveRoi.getPolygon();
   imp.startTiming();
   nextFontSize = defaultFontSize;
   nextLineWidth = 1;
   return flags;
 }
Example #14
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();
 }
Example #15
0
 boolean validDialogValues() {
   Calibration cal = imp.getCalibration();
   double pw = cal.pixelWidth, ph = cal.pixelHeight;
   if (width / pw < 1 || height / ph < 1) return false;
   if (xRoi / pw > imp.getWidth() || yRoi / ph > imp.getHeight()) return false;
   return true;
 }
Example #16
0
 /**
  * Creates a dialog box, allowing the user to enter the requested width, height, x & y
  * coordinates, slice number for a Region Of Interest, option for oval, and option for whether x &
  * y coordinates to be centered.
  */
 void showDialog() {
   Calibration cal = imp.getCalibration();
   int digits = 0;
   if (scaledUnits && cal.scaled()) digits = 2;
   Roi roi = imp.getRoi();
   if (roi == null) drawRoi();
   GenericDialog gd = new GenericDialog("Specify");
   gd.addNumericField("Width:", width, digits);
   gd.addNumericField("Height:", height, digits);
   gd.addNumericField("X coordinate:", xRoi, digits);
   gd.addNumericField("Y coordinate:", yRoi, digits);
   if (stackSize > 1) gd.addNumericField("Slice:", iSlice, 0);
   gd.addCheckbox("Oval", oval);
   gd.addCheckbox("Constrain square/circle", square);
   gd.addCheckbox("Centered", centered);
   if (cal.scaled()) {
     boolean unitsMatch = cal.getXUnit().equals(cal.getYUnit());
     String units = unitsMatch ? cal.getUnits() : cal.getXUnit() + " x " + cal.getYUnit();
     gd.addCheckbox("Scaled units (" + units + ")", scaledUnits);
   }
   fields = gd.getNumericFields();
   gd.addDialogListener(this);
   gd.showDialog();
   if (gd.wasCanceled()) {
     if (roi == null) imp.deleteRoi();
     else // *ALWAYS* restore initial ROI when cancelled
     imp.setRoi(roi);
   }
 }
 /**
  * Execute plugin functionality: stack FFT with window function, max projection over all slices
  * (phase, Z angle), blank out central 1/8 circle (set to min value), display min-max.
  */
 public ResultSet exec(ImagePlus... imps) {
   ImagePlus imp = imps[0];
   Util_StackFFT2D stackFFT2D = new Util_StackFFT2D();
   stackFFT2D.resultTypeChoice = Util_StackFFT2D.resultType[1];
   ImagePlus impF = stackFFT2D.exec(imp);
   IJ.run(impF, "Z Project...", "projection=[Max Intensity]");
   ImagePlus impProjF = ij.WindowManager.getCurrentImage();
   maskCentralRegion(impProjF);
   if (impProjF.isComposite()) {
     // display grayscale, not colored composite
     CompositeImage ci = (CompositeImage) impProjF;
     ci.setMode(IJ.GRAYSCALE);
     impProjF.updateAndDraw();
   }
   displayMinToMax(impProjF);
   impProjF.setTitle(I1l.makeTitle(imps[0], TLA));
   String shortInfo =
       "Maximum intensity projection of log"
           + " (amplitude^2) 2D FFT stack, central region masked,"
           + " rescaled (min-max) to improve contrast of the relevant"
           + " frequency range.";
   results.addImp(shortInfo, impProjF);
   results.addInfo(
       "How to interpret",
       "look for clean 1st & 2nd"
           + " order spots, similar across angles. Note that spot"
           + " intensity depends on image content.");
   return results;
 }
Example #18
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));
 }
Example #19
0
 private String getExifData(ImagePlus imp) {
   FileInfo fi = imp.getOriginalFileInfo();
   if (fi == null) return null;
   String directory = fi.directory;
   String name = fi.fileName;
   if (directory == null) return null;
   if ((name == null || name.equals("")) && imp.getStack().isVirtual())
     name = imp.getStack().getSliceLabel(imp.getCurrentSlice());
   if (name == null || !(name.endsWith("jpg") || name.endsWith("JPG"))) return null;
   String path = directory + name;
   String metadata = null;
   try {
     Class c = IJ.getClassLoader().loadClass("Exif_Reader");
     if (c == null) return null;
     String methodName = "getMetadata";
     Class[] argClasses = new Class[1];
     argClasses[0] = methodName.getClass();
     Method m = c.getMethod("getMetadata", argClasses);
     Object[] args = new Object[1];
     args[0] = path;
     Object obj = m.invoke(null, args);
     metadata = obj != null ? obj.toString() : null;
   } catch (Exception e) {
     return null;
   }
   if (metadata != null && !metadata.startsWith("Error:")) return metadata;
   else return null;
 }
 void updateSliceSummary() {
   int slices = imp.getStackSize();
   float[] areas = rt.getColumn(ResultsTable.AREA);
   if (areas == null) areas = new float[0];
   String label = imp.getTitle();
   if (slices > 1) {
     label = imp.getStack().getShortSliceLabel(slice);
     label = label != null && !label.equals("") ? label : "" + slice;
   }
   String aLine = null;
   double sum = 0.0;
   int start = areas.length - particleCount;
   if (start < 0) return;
   for (int i = start; i < areas.length; i++) sum += areas[i];
   int places = Analyzer.getPrecision();
   Calibration cal = imp.getCalibration();
   String total = "\t" + ResultsTable.d2s(sum, places);
   String average = "\t" + ResultsTable.d2s(sum / particleCount, places);
   String fraction = "\t" + ResultsTable.d2s(sum * 100.0 / totalArea, 1);
   aLine = label + "\t" + particleCount + total + average + fraction;
   aLine = addMeans(aLine, areas.length > 0 ? start : -1);
   if (slices == 1) {
     Frame frame = WindowManager.getFrame("Summary");
     if (frame != null && (frame instanceof TextWindow) && summaryHdr.equals(prevHdr))
       tw = (TextWindow) frame;
   }
   if (tw == null) {
     String title = slices == 1 ? "Summary" : "Summary of " + imp.getTitle();
     tw = new TextWindow(title, summaryHdr, aLine, 450, 300);
     prevHdr = summaryHdr;
   } else tw.append(aLine);
 }
Example #21
0
 /**
  * Adds a checkbox labelled "Preview" for "automatic" preview. The reference to this checkbox can
  * be retrieved by getPreviewCheckbox() and it provides the additional method previewRunning for
  * optical feedback while preview is prepared. PlugInFilters can have their "run" method
  * automatically called for preview under the following conditions: - the PlugInFilter must pass a
  * reference to itself (i.e., "this") as an argument to the AddPreviewCheckbox - it must implement
  * the DialogListener interface and set the filter parameters in the dialogItemChanged method. -
  * it must have DIALOG and PREVIEW set in its flags. A previewCheckbox is always off when the
  * filter is started and does not get recorded by the Macro Recorder.
  *
  * @param pfr A reference to the PlugInFilterRunner calling the PlugInFilter if automatic preview
  *     is desired, null otherwise.
  */
 public void addPreviewCheckbox(PlugInFilterRunner pfr) {
   if (previewCheckbox != null) return;
   ImagePlus imp = WindowManager.getCurrentImage();
   if (imp != null && imp.isComposite() && ((CompositeImage) imp).getMode() == IJ.COMPOSITE)
     return;
   this.pfr = pfr;
   addCheckbox(previewLabel, false, true);
 }
Example #22
0
 private ImagePlus duplicateImage(ImageProcessor iProcessor) {
   int w = iProcessor.getWidth();
   int h = iProcessor.getHeight();
   ImagePlus iPlus = NewImage.createByteImage("Image", w, h, 1, NewImage.FILL_BLACK);
   ImageProcessor imageProcessor = iPlus.getProcessor();
   imageProcessor.copyBits(iProcessor, 0, 0, Blitter.COPY);
   return iPlus;
 }
Example #23
0
 protected void hideRois() {
   if (currentImage == null) return;
   currentImage.killRoi();
   if (currentImage.isVisible()) {
     currentImage.updateAndDraw();
     ImageUtils.removeScrollListener(currentImage, this, this);
   }
   currentImage = null;
 }
Example #24
0
 /**
  * Builds dialog to query users for projection parameters.
  *
  * @param start starting slice to display
  * @param stop last slice
  */
 protected GenericDialog buildControlDialog(int start, int stop) {
   GenericDialog gd = new GenericDialog("ZProjection", IJ.getInstance());
   gd.addNumericField("Start slice:", startSlice, 0 /*digits*/);
   gd.addNumericField("Stop slice:", stopSlice, 0 /*digits*/);
   gd.addChoice("Projection type", METHODS, METHODS[method]);
   if (isHyperstack && imp.getNFrames() > 1 && imp.getNSlices() > 1)
     gd.addCheckbox("All time frames", allTimeFrames);
   return gd;
 }
Example #25
0
 /**
  * Zooms out by making the source rectangle (srcRect) larger and centering it on (x,y). If we
  * can't make it larger, then make the window smaller.
  */
 public void zoomOut(int x, int y) {
   if (magnification <= 0.03125) return;
   double oldMag = magnification;
   double newMag = getLowerZoomLevel(magnification);
   double srcRatio = (double) srcRect.width / srcRect.height;
   double imageRatio = (double) imageWidth / imageHeight;
   double initialMag = imp.getWindow().getInitialMagnification();
   if (Math.abs(srcRatio - imageRatio) > 0.05) {
     double scale = oldMag / newMag;
     int newSrcWidth = (int) Math.round(srcRect.width * scale);
     int newSrcHeight = (int) Math.round(srcRect.height * scale);
     if (newSrcWidth > imageWidth) newSrcWidth = imageWidth;
     if (newSrcHeight > imageHeight) newSrcHeight = imageHeight;
     int newSrcX = srcRect.x - (newSrcWidth - srcRect.width) / 2;
     int newSrcY = srcRect.y - (newSrcHeight - srcRect.height) / 2;
     if (newSrcX < 0) newSrcX = 0;
     if (newSrcY < 0) newSrcY = 0;
     srcRect = new Rectangle(newSrcX, newSrcY, newSrcWidth, newSrcHeight);
     // IJ.log(newMag+" "+srcRect+" "+dstWidth+" "+dstHeight);
     int newDstWidth = (int) (srcRect.width * newMag);
     int newDstHeight = (int) (srcRect.height * newMag);
     setMagnification(newMag);
     setMaxBounds();
     // IJ.log(newDstWidth+" "+dstWidth+" "+newDstHeight+" "+dstHeight);
     if (newDstWidth < dstWidth || newDstHeight < dstHeight) {
       // IJ.log("pack");
       setDrawingSize(newDstWidth, newDstHeight);
       imp.getWindow().pack();
     } else repaint();
     return;
   }
   if (imageWidth * newMag > dstWidth) {
     int w = (int) Math.round(dstWidth / newMag);
     if (w * newMag < dstWidth) w++;
     int h = (int) Math.round(dstHeight / newMag);
     if (h * newMag < dstHeight) h++;
     x = offScreenX(x);
     y = offScreenY(y);
     Rectangle r = new Rectangle(x - w / 2, y - h / 2, w, h);
     if (r.x < 0) r.x = 0;
     if (r.y < 0) r.y = 0;
     if (r.x + w > imageWidth) r.x = imageWidth - w;
     if (r.y + h > imageHeight) r.y = imageHeight - h;
     srcRect = r;
   } else {
     srcRect = new Rectangle(0, 0, imageWidth, imageHeight);
     setDrawingSize((int) (imageWidth * newMag), (int) (imageHeight * newMag));
     // setDrawingSize(dstWidth/2, dstHeight/2);
     imp.getWindow().pack();
   }
   // IJ.write(newMag + " " + srcRect.x+" "+srcRect.y+" "+srcRect.width+" "+srcRect.height+"
   // "+dstWidth + " " + dstHeight);
   setMagnification(newMag);
   // IJ.write(srcRect.x + " " + srcRect.width + " " + dstWidth);
   setMaxBounds();
   repaint();
 }
Example #26
0
  void Bernsen(ImagePlus imp, int radius, double par1, double par2, boolean doIwhite) {
    // Bernsen recommends WIN_SIZE = 31 and CONTRAST_THRESHOLD = 15.
    //  1) Bernsen J. (1986) "Dynamic Thresholding of Grey-Level Images"
    //    Proc. of the 8th Int. Conf. on Pattern Recognition, pp. 1251-1255
    //  2) Sezgin M. and Sankur B. (2004) "Survey over Image Thresholding
    //   Techniques and Quantitative Performance Evaluation" Journal of
    //   Electronic Imaging, 13(1): 146-165
    //  http://citeseer.ist.psu.edu/sezgin04survey.html
    // Ported to ImageJ plugin from E Celebi's fourier_0.8 routines
    // This version uses a circular local window, instead of a rectagular one
    ImagePlus Maximp, Minimp;
    ImageProcessor ip = imp.getProcessor(), ipMax, ipMin;
    int contrast_threshold = 15;
    int local_contrast;
    int mid_gray;
    byte object;
    byte backg;
    int temp;

    if (par1 != 0) {
      IJ.log("Bernsen: changed contrast_threshold from :" + contrast_threshold + "  to:" + par1);
      contrast_threshold = (int) par1;
    }

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

    Maximp = duplicateImage(ip);
    ipMax = Maximp.getProcessor();
    RankFilters rf = new RankFilters();
    rf.rank(ipMax, radius, rf.MAX); // Maximum
    // Maximp.show();
    Minimp = duplicateImage(ip);
    ipMin = Minimp.getProcessor();
    rf.rank(ipMin, radius, rf.MIN); // Minimum
    // Minimp.show();
    byte[] pixels = (byte[]) ip.getPixels();
    byte[] max = (byte[]) ipMax.getPixels();
    byte[] min = (byte[]) ipMin.getPixels();

    for (int i = 0; i < pixels.length; i++) {
      local_contrast = (int) ((max[i] & 0xff) - (min[i] & 0xff));
      mid_gray = (int) ((min[i] & 0xff) + (max[i] & 0xff)) / 2;
      temp = (int) (pixels[i] & 0x0000ff);
      if (local_contrast < contrast_threshold)
        pixels[i] = (mid_gray >= 128) ? object : backg; // Low contrast region
      else pixels[i] = (temp >= mid_gray) ? object : backg;
    }
    // imp.updateAndDraw();
    return;
  }
Example #27
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));
 }
Example #28
0
 public ImagePlus groupZProject(ImagePlus imp, int method, int groupSize) {
   if (method < 0 || method >= ZProjector.METHODS.length) return null;
   imp.setDimensions(1, groupSize, imp.getStackSize() / groupSize);
   ZProjector zp = new ZProjector(imp);
   zp.setMethod(method);
   zp.setStartSlice(1);
   zp.setStopSlice(groupSize);
   zp.doHyperStackProjection(true);
   return zp.getProjection();
 }
Example #29
0
 protected void updateRoi() {
   // System.out.println("image:"+currentImage.getTitle()+ " slice:"+currentImage.getSlice());
   Roi r = currentROIs.get(currentImage.getSlice());
   if (r != null) {
     currentImage.setRoi(r);
   } else {
     currentImage.killRoi();
   }
   currentImage.updateAndDraw();
 }
Example #30
0
 void hide() {
   ImagePlus imp = IJ.getImage();
   Overlay overlay = imp.getOverlay();
   if (overlay != null) {
     overlay2 = overlay;
     imp.setOverlay(null);
   }
   RoiManager rm = RoiManager.getInstance();
   if (rm != null) rm.runCommand("show none");
 }