Esempio 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) {
     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();
 }
Esempio n. 2
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;
 }
Esempio n. 3
0
 public void run(String arg) {
   imp = WindowManager.getCurrentImage();
   if (arg.equals("add")) {
     addToRoiManager(imp);
     return;
   }
   if (imp == null) {
     IJ.noImage();
     return;
   }
   if (arg.equals("all")) imp.setRoi(0, 0, imp.getWidth(), imp.getHeight());
   else if (arg.equals("none")) imp.killRoi();
   else if (arg.equals("restore")) imp.restoreRoi();
   else if (arg.equals("spline")) fitSpline();
   else if (arg.equals("circle")) fitCircle(imp);
   else if (arg.equals("ellipse")) createEllipse(imp);
   else if (arg.equals("hull")) convexHull(imp);
   else if (arg.equals("mask")) createMask(imp);
   else if (arg.equals("from")) createSelectionFromMask(imp);
   else if (arg.equals("inverse")) invert(imp);
   else if (arg.equals("toarea")) lineToArea(imp);
   else if (arg.equals("toline")) areaToLine(imp);
   else if (arg.equals("properties")) {
     setProperties("Properties ", imp.getRoi());
     imp.draw();
   } else if (arg.equals("band")) makeBand(imp);
   else if (arg.equals("tobox")) toBoundingBox(imp);
   else runMacro(arg);
 }
Esempio n. 4
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);
  }
Esempio n. 5
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;
  }
Esempio n. 6
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.");
  }
Esempio n. 7
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));
 }
Esempio n. 8
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;
 }
Esempio n. 9
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();
 }
Esempio n. 10
0
 private void doRGBProjection(ImageStack stack) {
   ImageStack[] channels = ChannelSplitter.splitRGB(stack, true);
   ImagePlus red = new ImagePlus("Red", channels[0]);
   ImagePlus green = new ImagePlus("Green", channels[1]);
   ImagePlus blue = new ImagePlus("Blue", channels[2]);
   imp.unlock();
   ImagePlus saveImp = imp;
   imp = red;
   color = "(red)";
   doProjection();
   ImagePlus red2 = projImage;
   imp = green;
   color = "(green)";
   doProjection();
   ImagePlus green2 = projImage;
   imp = blue;
   color = "(blue)";
   doProjection();
   ImagePlus blue2 = projImage;
   int w = red2.getWidth(), h = red2.getHeight(), d = red2.getStackSize();
   if (method == SD_METHOD) {
     ImageProcessor r = red2.getProcessor();
     ImageProcessor g = green2.getProcessor();
     ImageProcessor b = blue2.getProcessor();
     double max = 0;
     double rmax = r.getStatistics().max;
     if (rmax > max) max = rmax;
     double gmax = g.getStatistics().max;
     if (gmax > max) max = gmax;
     double bmax = b.getStatistics().max;
     if (bmax > max) max = bmax;
     double scale = 255 / max;
     r.multiply(scale);
     g.multiply(scale);
     b.multiply(scale);
     red2.setProcessor(r.convertToByte(false));
     green2.setProcessor(g.convertToByte(false));
     blue2.setProcessor(b.convertToByte(false));
   }
   RGBStackMerge merge = new RGBStackMerge();
   ImageStack stack2 =
       merge.mergeStacks(w, h, d, red2.getStack(), green2.getStack(), blue2.getStack(), true);
   imp = saveImp;
   projImage = new ImagePlus(makeTitle(), stack2);
 }
Esempio n. 11
0
 public void doHyperStackProjection(boolean allTimeFrames) {
   int start = startSlice;
   int stop = stopSlice;
   int firstFrame = 1;
   int lastFrame = imp.getNFrames();
   if (!allTimeFrames) firstFrame = lastFrame = imp.getFrame();
   ImageStack stack = new ImageStack(imp.getWidth(), imp.getHeight());
   int channels = imp.getNChannels();
   int slices = imp.getNSlices();
   if (slices == 1) {
     slices = imp.getNFrames();
     firstFrame = lastFrame = 1;
   }
   int frames = lastFrame - firstFrame + 1;
   increment = channels;
   boolean rgb = imp.getBitDepth() == 24;
   for (int frame = firstFrame; frame <= lastFrame; frame++) {
     for (int channel = 1; channel <= channels; channel++) {
       startSlice = (frame - 1) * channels * slices + (start - 1) * channels + channel;
       stopSlice = (frame - 1) * channels * slices + (stop - 1) * channels + channel;
       if (rgb) doHSRGBProjection(imp);
       else doProjection();
       stack.addSlice(null, projImage.getProcessor());
     }
   }
   projImage = new ImagePlus(makeTitle(), stack);
   projImage.setDimensions(channels, 1, frames);
   if (channels > 1) {
     projImage = new CompositeImage(projImage, 0);
     ((CompositeImage) projImage).copyLuts(imp);
     if (method == SUM_METHOD || method == SD_METHOD)
       ((CompositeImage) projImage).resetDisplayRanges();
   }
   if (frames > 1) projImage.setOpenAsHyperStack(true);
   Overlay overlay = imp.getOverlay();
   if (overlay != null) {
     startSlice = start;
     stopSlice = stop;
     if (imp.getType() == ImagePlus.COLOR_RGB)
       projImage.setOverlay(projectRGBHyperStackRois(overlay));
     else projImage.setOverlay(projectHyperStackRois(overlay));
   }
   IJ.showProgress(1, 1);
 }
Esempio n. 12
0
 // Finds the index of the upper right point that is guaranteed to be on convex hull
 int findFirstPoint(int[] xCoordinates, int[] yCoordinates, int n, ImagePlus imp) {
   int smallestY = imp.getHeight();
   int x, y;
   for (int i = 0; i < n; i++) {
     y = yCoordinates[i];
     if (y < smallestY) smallestY = y;
   }
   int smallestX = imp.getWidth();
   int p1 = 0;
   for (int i = 0; i < n; i++) {
     x = xCoordinates[i];
     y = yCoordinates[i];
     if (y == smallestY && x < smallestX) {
       smallestX = x;
       p1 = i;
     }
   }
   return p1;
 }
Esempio n. 13
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;
 }
  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;
  }
Esempio n. 15
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
  }
Esempio n. 16
0
  public int setup(String arg, ImagePlus imp) {
    // IJ.register(Average_Oversampled.class);

    if (IJ.versionLessThan("1.32c")) return DONE;

    if (this.pre) { // before finding means

      imp.unlock();
      this.imp = imp;
      this.nslices = imp.getNSlices();
      this.width = imp.getWidth();
      this.height = imp.getHeight();
      this.slicecols = new float[nslices][width];
      this.pre = false;
      return (DOES_ALL + DOES_STACKS + FINAL_PROCESSING);

    } else { // find SD after finding means of columns
      float sum; // sum of pixel values column
      float avg; // average pixel value of a column
      double devsum; // sum of deviations
      double devavg; // standard deviation
      double[] columns = new double[width]; // x-axis of plot
      double[] sdevs = new double[width]; // y-axis of plot

      for (int i = 0; i < width; i += 1) {
        sum = 0; // reset with each column
        avg = 0; // reset with each column
        devsum = 0; // reset with each column
        devavg = 0; // reset with each column
        columns[i] = i; // building x-axis

        for (int s = 0; s < nslices; s += 1) { // sum of column means
          sum = sum + slicecols[s][i];
        }
        avg = sum / nslices; // mean of one column across all slices

        for (int s = 0; s < nslices; s += 1) { // standard deviation
          devsum = devsum + Math.pow((slicecols[s][i] - avg), 2); // square diff
        }
        devavg = Math.sqrt(devsum / nslices);

        sdevs[i] = devavg; // building y-axis
      }

      Plot plot = new Plot("Average SD by Column", "Columns", "Standard Deviation", columns, sdevs);
      plot.show();

      // calculate CTN
      double ctn;
      double sdevssum = 0;
      for (double sd : sdevs) {
        sdevssum = sdevssum + sd;
      }
      ctn = sdevssum / width;

      // display CTN on results table
      ResultsTable rt = ResultsTable.getResultsTable();
      // rt.incrementCounter();
      rt.addValue("Column Temporal Noise", ctn);
      rt.show("Results");

      this.pre = false;

      return DONE;
    }
  }