void showResults() {
   int count = rt.getCounter();
   // if (count==0) return;
   boolean lastSlice = !processStack || slice == imp.getStackSize();
   if ((showChoice == OVERLAY_OUTLINES || showChoice == OVERLAY_MASKS) && slice == 1 && count > 0)
     imp.setOverlay(overlay);
   else if (outlines != null && lastSlice) {
     String title = imp != null ? imp.getTitle() : "Outlines";
     String prefix;
     if (showChoice == MASKS) prefix = "Mask of ";
     else if (showChoice == ROI_MASKS) prefix = "Count Masks of ";
     else prefix = "Drawing of ";
     outlines.update(drawIP);
     outputImage = new ImagePlus(prefix + title, outlines);
     if (inSituShow) {
       if (imp.getStackSize() == 1) Undo.setup(Undo.TRANSFORM, imp);
       imp.setStack(null, outputImage.getStack());
     } else if (!hideOutputImage) outputImage.show();
   }
   if (showResults && !processStack) {
     TextPanel tp = IJ.getTextPanel();
     if (beginningCount > 0 && tp != null && tp.getLineCount() != count) rt.show("Results");
     Analyzer.firstParticle = beginningCount;
     Analyzer.lastParticle = Analyzer.getCounter() - 1;
   } else Analyzer.firstParticle = Analyzer.lastParticle = 0;
 }
 /**
  * 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 #3
0
 void loadTransformation(String filename, ResultsTable res) {
   try {
     String line;
     FileReader fr = new FileReader(filename);
     BufferedReader br = new BufferedReader(fr);
     if (!br.readLine().equals(" 	Z-Step	Raw Width minus Heigh	Calibration Width minus Height")) {
       IJ.error("File does not seam to be an Astigmatism calibration file");
       return;
     }
     // java.lang.String [] elements = new java.lang.String [3];
     java.lang.String[] elements;
     int counter = 1;
     res.reset();
     while ((line = br.readLine()) != null) {
       IJ.showStatus("Loading element " + counter + "... sit back and relax.");
       counter++;
       line.trim();
       elements = line.split("\t");
       res.incrementCounter();
       res.addValue("Z-Step", Double.parseDouble(elements[1]));
       res.addValue("Raw Width minus Heigh", Double.parseDouble(elements[2]));
       res.addValue("Calibration Width minus Height", Double.parseDouble(elements[3]));
     }
     fr.close();
   } catch (FileNotFoundException e) {
     IJ.error("File not found exception" + e);
     return;
   } catch (IOException e) {
     IJ.error("IOException exception" + e);
     return;
   } catch (NumberFormatException e) {
     IJ.error("Number format exception" + e);
     return;
   }
 }
  /**
   * A table of x-values, y-values and the counts is generated and returned as a string. The single
   * fields in one row (X Y Count) are separated by tabs.
   *
   * @return A String representation of the histogram data.
   */
  public String getData() {
    StringBuffer sb = new StringBuffer();

    double xBinWidth = 1.0 / getXBinWidth();
    double yBinWidth = 1.0 / getYBinWidth();
    double xMin = getXMin();
    double yMin = getYMin();
    // check if we have bins of size one or other ones
    boolean xBinWidthIsOne = Math.abs(xBinWidth - 1.0) < 0.00001;
    boolean yBinWidthIsOne = Math.abs(yBinWidth - 1.0) < 0.00001;
    // configure decimal places accordingly
    int xDecimalPlaces = xBinWidthIsOne ? 0 : 3;
    int yDecimalPlaces = yBinWidthIsOne ? 0 : 3;
    // create a cursor to access the histogram data
    RandomAccess<LongType> cursor = plotImage.randomAccess();
    // loop over 2D histogram
    for (int i = 0; i < plotImage.dimension(0); ++i) {
      for (int j = 0; j < plotImage.dimension(1); ++j) {
        cursor.setPosition(i, 0);
        cursor.setPosition(j, 1);
        sb.append(
            ResultsTable.d2s(xMin + (i * xBinWidth), xDecimalPlaces)
                + "\t"
                + ResultsTable.d2s(yMin + (j * yBinWidth), yDecimalPlaces)
                + "\t"
                + ResultsTable.d2s(cursor.get().getRealDouble(), 0)
                + "\n");
      }
    }

    return sb.toString();
  }
 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 #6
0
 /** Opens a tab or comma delimited text file in the Results window. */
 public static void openResultsTable(String path) {
   try {
     ResultsTable rt = ResultsTable.open(path);
     if (rt != null) rt.show("Results");
   } catch (IOException e) {
     IJ.error("Open Results", e.getMessage());
   }
 }
Example #7
0
 void loadParticleResults(String filename, ResultsTable res) {
   try {
     String line;
     FileReader fr = new FileReader(filename);
     BufferedReader br = new BufferedReader(fr);
     java.lang.String header =
         " 	Intensity	X (px)	Y (px)	X (nm)	Y (nm)	Z (nm)	Left-Width(px)	Right-Width (px)	Up-Height (px)	Down-Height (px)	X Symmetry (%)	Y Symmetry (%)	Width minus Height (px)	Frame Number";
     java.lang.String firstline = br.readLine();
     if (!firstline.contains("X (px)	Y (px)	X (nm)	Y (nm)	Z (nm)")) {
       IJ.error("File does not seam to be a Particles Table file");
       IJ.log("Found header: " + firstline);
       IJ.log("Expecting: " + header);
       return;
     }
     res.reset();
     int counter = 1;
     java.util.concurrent.locks.Lock lock = new java.util.concurrent.locks.ReentrantLock();
     ThreadedLoader tloader = new ThreadedLoader();
     // java.lang.String txt = fr.read();
     while ((line = br.readLine()) != null) {
       tloader = new ThreadedLoader();
       tloader.mysetup(res, lock, line);
       tloader.start();
       IJ.showStatus("Loading particle " + counter + "... sit back and relax.");
       counter++;
     }
     try {
       tloader.join();
     } catch (Exception e) {
       IJ.error("" + e);
     }
     if (res.getCounter() < 5000000) {
       IJ.showStatus("Creating particle table, this should take a few seconds...");
       res.show("Results");
     } else
       IJ.showMessage(
           "Warning",
           "Results table has too many particles, they will not be shown but the data still exists within it\nyou can still use all the plugin functionality or save table changes though the 'Save Particle Table' command.");
     fr.close();
     IJ.showStatus("Done loading table...");
   } catch (FileNotFoundException e) {
     IJ.error("File not found exception" + e);
     return;
   } catch (IOException e) {
     IJ.error("IOException exception" + e);
     return;
   } catch (NumberFormatException e) {
     IJ.error("Number format exception" + e);
     return;
   }
 }
 void drawOutline(ImageProcessor ip, Roi roi, int count) {
   if (showChoice == OVERLAY_OUTLINES || showChoice == OVERLAY_MASKS) {
     if (overlay == null) {
       overlay = new Overlay();
       overlay.drawLabels(true);
       overlay.setLabelFont(new Font("SansSerif", Font.PLAIN, fontSize));
     }
     Roi roi2 = (Roi) roi.clone();
     roi2.setStrokeColor(Color.cyan);
     if (lineWidth != 1) roi2.setStrokeWidth(lineWidth);
     if (showChoice == OVERLAY_MASKS) roi2.setFillColor(Color.cyan);
     overlay.add(roi2);
   } else {
     Rectangle r = roi.getBounds();
     int nPoints = ((PolygonRoi) roi).getNCoordinates();
     int[] xp = ((PolygonRoi) roi).getXCoordinates();
     int[] yp = ((PolygonRoi) roi).getYCoordinates();
     int x = r.x, y = r.y;
     if (!inSituShow) ip.setValue(0.0);
     ip.moveTo(x + xp[0], y + yp[0]);
     for (int i = 1; i < nPoints; i++) ip.lineTo(x + xp[i], y + yp[i]);
     ip.lineTo(x + xp[0], y + yp[0]);
     if (showChoice != BARE_OUTLINES) {
       String s = ResultsTable.d2s(count, 0);
       ip.moveTo(r.x + r.width / 2 - ip.getStringWidth(s) / 2, r.y + r.height / 2 + fontSize / 2);
       if (!inSituShow) ip.setValue(1.0);
       ip.drawString(s);
     }
   }
 }
Example #9
0
  private void writeChecksum(StringBuffer sb1, StringBuffer sb2, ResultsTable table, int row) {
    if (sb1.toString().equals(sb2.toString())) {

      System.out.println("Checksum Match!" + sb1.toString());
      // table.addValue("CheckSum", "Safe");
      table.setValue("Checksum", row, sb1.toString());
      // table.addValue("CheckSum", sb1.toString());
      // table.incrementCounter();
    } else {

      //	System.out.println("Checksum Match! Image may be damaged!"+ " : " + t);
      // i = i-1;
      // table.addValue("CheckSum", "Damaged");
      table.setValue("Checksum", row, "Damaged");
      // table.incrementCounter();
    }
  }
 private String addMean(int column, String line, int start) {
   if (start == -1) {
     line += "\tNaN";
     summaryHdr += "\t" + ResultsTable.getDefaultHeading(column);
   } else {
     float[] c = column >= 0 ? rt.getColumn(column) : null;
     if (c != null) {
       ImageProcessor ip = new FloatProcessor(c.length, 1, c, null);
       if (ip == null) return line;
       ip.setRoi(start, 0, ip.getWidth() - start, 1);
       ip = ip.crop();
       ImageStatistics stats = new FloatStatistics(ip);
       if (stats == null) return line;
       line += n(stats.mean);
     } else line += "\tNaN";
     summaryHdr += "\t" + rt.getColumnHeading(column);
   }
   return line;
 }
Example #11
0
 /** Opens a tab or comma delimited text file. */
 public static void openTable(String path) {
   String name = "";
   if (path == null || path.equals("")) {
     OpenDialog od = new OpenDialog("Open Table...");
     String dir = od.getDirectory();
     name = od.getFileName();
     if (name == null) return;
     else path = dir + name;
   }
   try {
     ResultsTable rt = ResultsTable.open(path);
     if (rt != null) {
       rt.showRowNumbers(false);
       rt.show(name);
     }
   } catch (IOException e) {
     IJ.error("Open Table", e.getMessage());
   }
 }
 /**
  * Draws a selected particle in a separate image. This is another method subclasses may want to
  * override.
  */
 protected void drawParticle(
     ImageProcessor drawIP, Roi roi, ImageStatistics stats, ImageProcessor mask) {
   switch (showChoice) {
     case MASKS:
       drawFilledParticle(drawIP, roi, mask);
       break;
     case OUTLINES:
     case BARE_OUTLINES:
     case OVERLAY_OUTLINES:
     case OVERLAY_MASKS:
       drawOutline(drawIP, roi, rt.getCounter());
       break;
     case ELLIPSES:
       drawEllipse(drawIP, stats, rt.getCounter());
       break;
     case ROI_MASKS:
       drawRoiFilledParticle(drawIP, roi, mask, rt.getCounter());
       break;
     default:
   }
 }
Example #13
0
 final void addResults(final ResultsTable rt, final Calibration cal, final double nameid) {
   for (int i = 0; i < n_points; i++) {
     final Layer la = layer_set.getLayer(p_layer[i]);
     if (null == layer) {
       Utils.log("Dissector.addResults: could not find layer with id " + p_layer[i]);
       continue;
     }
     final Point2D.Double po = M.transform(Dissector.this.at, p[0][i], p[1][i]);
     rt.incrementCounter();
     rt.addLabel("units", cal.getUnit());
     rt.addValue(0, Dissector.this.id);
     rt.addValue(1, tag);
     rt.addValue(2, po.x * cal.pixelWidth);
     rt.addValue(3, po.y * cal.pixelHeight);
     rt.addValue(4, la.getZ() * cal.pixelWidth); // layer Z is in pixels
     rt.addValue(5, radius * cal.pixelWidth);
     rt.addValue(6, nameid);
   }
 }
Example #14
0
  public static void main(String[] args) {
    String mriImage = args[0];
    String outImage = args[1];
    String segArgs = args[2];
    String outTable = args[3];
    String pdxArgs = args[4];

    System.out.println("Open: " + mriImage);
    IJ.open(mriImage);
    COPD_LungSegment tjPlug = new COPD_LungSegment();
    ImagePlus cImage = IJ.getImage();
    tjPlug.setup(segArgs, cImage);
    tjPlug.run(cImage.getProcessor());
    IJ.save(cImage, outImage);
    COPD_PDxLAAx pdxPlug = new COPD_PDxLAAx();
    pdxPlug.setup("", cImage);
    pdxPlug.run(cImage.getProcessor());
    ResultsTable rt = Analyzer.getResultsTable();
    try {
      rt.saveAs(outTable);
    } catch (IOException e) {
      e.printStackTrace();
    }

    System.out.println("Results Table\n");
    String prefix = "rtout, ";

    for (int i = 0; i < ResultsTable.MAX_COLUMNS; i++) {
      if (!rt.columnExists(i)) break;
      String tempOut = rt.getColumnHeading(i);
      for (double d : rt.getColumnAsDoubles(i)) {
        tempOut += ", " + d;
      }
      System.out.println(prefix + tempOut);
    }
  }
Example #15
0
  private void CopyAllFiles(String csvFilename) throws IOException, NoSuchAlgorithmException {
    ResultsTable table = ResultsTable.open(csvFilename);

    int size = table.getCounter();
    for (int i = 0; i < size; i++) {
      String source = table.getStringValue("OriginaFile", i);
      String destination = table.getStringValue("WorkingFile", i);
      print(i + 1 + " Move from: " + source + " to ------> " + destination);
      // print("to ------> " + destination);
      // imp =  new ImagePlus(source);
      // IJ.save(imp, destination);
      CopyFile(source, destination);
      StringBuffer sb1 = CheckSum(source);
      StringBuffer sb2 = CheckSum(destination);
      // CheckSum(source);
      // check SHA1
      writeChecksum(sb1, sb2, table, i);
    }
    table.saveAs(csvFilename);
  }
Example #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;
    }
  }
Example #17
0
  public void run() {
    line.trim();
    elements = line.split("\t");
    if (elements.length < 14) return;

    lock.lock();
    res.incrementCounter();
    res.addValue("Intensity", Double.parseDouble(elements[1]));
    res.addValue("X (px)", Double.parseDouble(elements[2]));
    res.addValue("Y (px)", Double.parseDouble(elements[3]));
    res.addValue("X (nm)", Double.parseDouble(elements[4]));
    res.addValue("Y (nm)", Double.parseDouble(elements[5]));
    res.addValue("Z (nm)", Double.parseDouble(elements[6]));
    res.addValue("Left-StdDev (px)", Double.parseDouble(elements[7]));
    res.addValue("Right-StdDev (px)", Double.parseDouble(elements[8]));
    res.addValue("Up-StdDev (px)", Double.parseDouble(elements[9]));
    res.addValue("Down-StdDev (px)", Double.parseDouble(elements[10]));
    res.addValue("X Symmetry (%)", Double.parseDouble(elements[11]));
    res.addValue("Y Symmetry (%)", Double.parseDouble(elements[12]));
    res.addValue("Width minus Height (px)", Double.parseDouble(elements[13]));
    res.addValue("Frame Number", Double.parseDouble(elements[14]));
    lock.unlock();
  }
  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;
  }
Example #19
0
 // show results table
 void showTable() {
   ptable.show("Results");
 }
Example #20
0
  // function fitting particles in specific frame
  void fitParticles(
      ImageProcessor ipRaw,
      SMLDialog fdg,
      double[][] particles_,
      int nFrame,
      Overlay SpotsPositions__) {
    int width = ipRaw.getWidth();
    int height = ipRaw.getHeight();
    int x, y, i, j, nCount, nParticlesCount, nParticlesNumber;
    double xCentroid, yCentroid, xSD, ySD;
    double dIntAmp, dIntNoise;
    double dIntAverage, dIntDev;
    double dIMax, dIMin, dInt;
    double dNoiseAvrg, dNoiseSD;
    double dSNR;
    int dBorder; // radius in pixels around center point to fit Gaussian
    double nFalsePositive;

    double[][] spotInt;
    double[][] spotXpos;
    double[][] spotYpos;
    double[] dFitParams;
    double dErrCoeff;
    LevenbergMarquardt SMLlma = new LevenbergMarquardt();
    // LMA SMLlma;
    // SMLTwoDGaussian GFit = new SMLTwoDGaussian();
    OvalRoi spotROI;

    // initialization
    dBorder = (int) (fdg.dPSFsigma * DOMConstants.FITRADIUS);
    spotInt = new double[(2 * dBorder + 1)][(2 * dBorder + 1)];
    spotXpos = new double[(2 * dBorder + 1)][(2 * dBorder + 1)];
    spotYpos = new double[(2 * dBorder + 1)][(2 * dBorder + 1)];
    dFitParams = new double[6];

    nParticlesNumber = particles_[0].length;

    for (nParticlesCount = 0; nParticlesCount < nParticlesNumber; nParticlesCount++) {

      // creating array of intensity values for fitting
      nCount = 0;
      dIMin = Double.MAX_VALUE;
      dIMax = -100;

      dIntAverage = 0;

      for (x = 0, i = (int) (Math.round(particles_[0][nParticlesCount]) - dBorder);
          i <= Math.round(particles_[0][nParticlesCount]) + dBorder;
          ++x, i++)
        for (y = 0, j = (int) (Math.round(particles_[1][nParticlesCount]) - dBorder);
            j <= Math.round(particles_[1][nParticlesCount]) + dBorder;
            ++y, j++) {
          dInt = ipRaw.getPixel(i, j);
          spotInt[y][x] = dInt;
          spotXpos[y][x] = (double) i;
          spotYpos[y][x] = (double) j;
          if (dInt > dIMax) dIMax = dInt;
          if (dInt < dIMin) dIMin = dInt;
          nCount++;
          dIntAverage += dInt;
        }
      // calculate deviation from average intensity
      dIntAverage = dIntAverage / nCount;
      dIntDev = 0;
      for (x = 0, i = (int) (Math.round(particles_[0][nParticlesCount]) - dBorder);
          i <= Math.round(particles_[0][nParticlesCount]) + dBorder;
          ++x, i++)
        for (y = 0, j = (int) (Math.round(particles_[1][nParticlesCount]) - dBorder);
            j <= Math.round(particles_[1][nParticlesCount]) + dBorder;
            ++y, j++) {
          dIntDev += Math.pow(ipRaw.getPixel(i, j) - dIntAverage, 2);
        }

      // initial values of fitting parameters
      // dFitParams[0]= particles_[3][nParticlesCount]; //minimum, background level
      // dFitParams[1]= particles_[2][nParticlesCount] - particles_[3][nParticlesCount]; //
      // intensity amplitude, max-min
      dFitParams[0] = dIMin; // minimum, background level
      dFitParams[1] = dIMax - dIMin; // intensity amplitude, max-min

      dFitParams[2] = particles_[0][nParticlesCount]; // x center
      dFitParams[3] = particles_[1][nParticlesCount]; // y center
      dFitParams[4] = fdg.dPSFsigma;
      dFitParams[5] = fdg.dPSFsigma;
      nFalsePositive = 0.0;
      // SMLlma = new LMA(GFit, dFitParams, spotInt);
      // SMLlma.setMaxIterations(fdg.nIterations);
      double[] fitted_parameters = new double[6];
      double[] fit_errors = new double[6];
      double chi2_fit = 0.0;

      // fitting
      fitted_parameters =
          SMLlma.run(
              spotInt,
              spotXpos,
              spotYpos,
              2 * dBorder + 1,
              2 * dBorder + 1,
              dFitParams,
              fdg.nIterations,
              0.001);
      fit_errors =
          SMLlma.calculateStandardErrors(
              spotInt, spotXpos, spotYpos, 2 * dBorder + 1, 2 * dBorder + 1, fitted_parameters);
      chi2_fit =
          SMLlma.calculateChi2(
              spotInt, spotXpos, spotYpos, 2 * dBorder + 1, 2 * dBorder + 1, fitted_parameters);

      dErrCoeff = Math.sqrt(chi2_fit / (nCount - 6));
      for (i = 0; i < 6; i++) fit_errors[i] *= dErrCoeff;

      // checking for false positives

      // spot is too big or too small
      xSD = Math.abs(fitted_parameters[4]);
      ySD = Math.abs(fitted_parameters[5]);
      if ((xSD > 1.3 * fdg.dPSFsigma)
          || (xSD < 0.70 * fdg.dPSFsigma)
          || (ySD < 0.70 * fdg.dPSFsigma)
          || (ySD > 1.3 * fdg.dPSFsigma)) nFalsePositive = 1.0;

      // localization precision is bigger than PSF size
      if ((fit_errors[2] > fdg.dPSFsigma) || (fit_errors[3] > fdg.dPSFsigma)) nFalsePositive = 1.0;

      // fitting went out of fitting region
      if (Math.sqrt(
              Math.pow(particles_[0][nParticlesCount] - fitted_parameters[2], 2)
                  + Math.pow(particles_[1][nParticlesCount] - fitted_parameters[3], 2))
          > fdg.dPSFsigma * DOMConstants.FITRADIUS) nFalsePositive = 1.0;

      dIntAmp = 0;
      dIntNoise = 0;
      dNoiseAvrg = 0;
      dNoiseSD = 0;
      dSNR = 0;
      xCentroid = Math.round(fitted_parameters[2] + 0.5); // 0.5 is for correction of pixel shift
      yCentroid = Math.round(fitted_parameters[3] + 0.5);

      // calculating integrated spot intensity and estimating SNR
      xSD = Math.round(fdg.dPSFsigma * DOMConstants.FITRADIUS);
      ySD = Math.round(fdg.dPSFsigma * DOMConstants.FITRADIUS);

      if (((xCentroid - xSD - 1) > 0)
          && ((yCentroid - ySD - 1) > 0)
          && ((xCentroid + xSD + 1) < (width - 1))
          && ((yCentroid + ySD + 1) < (height - 1))) {
        // integrated intensity in 3SD * 3SD region
        for (i = (int) (xCentroid - xSD); i <= (int) (xCentroid + xSD); i++)
          for (j = (int) (yCentroid - ySD); j <= (int) (yCentroid + ySD); j++) {
            dIntAmp += ipRaw.getPixel(i, j);
          }

        // averaged noise around spot

        j = (int) (yCentroid - ySD - 1);
        for (i = (int) (xCentroid - xSD - 1); i <= (int) (xCentroid + xSD + 1); i++) {
          dIntNoise += ipRaw.getPixel(i, j);
        }
        j = (int) (yCentroid + ySD + 1);
        for (i = (int) (xCentroid - xSD - 1); i <= (int) (xCentroid + xSD + 1); i++) {
          dIntNoise += ipRaw.getPixel(i, j);
        }
        i = (int) (xCentroid - xSD - 1);
        for (j = (int) (yCentroid - ySD); j <= (int) (yCentroid + ySD); j++) {
          dIntNoise += ipRaw.getPixel(i, j);
        }
        i = (int) (xCentroid + xSD + 1);
        for (j = (int) (yCentroid - ySD); j <= (int) (yCentroid + ySD); j++) {
          dIntNoise += ipRaw.getPixel(i, j);
        }
        dNoiseAvrg = dIntNoise / (4 * xSD + 4 * ySD + 8);
        dIntAmp = dIntAmp - (dNoiseAvrg * ((2 * xSD + 1) * (2 * ySD + 1)));

        // SD of noise
        j = (int) (yCentroid - ySD - 1);
        for (i = (int) (xCentroid - xSD - 1); i <= (int) (xCentroid + xSD + 1); i++)
          dNoiseSD += Math.pow(dNoiseAvrg - ipRaw.getPixel(i, j), 2);
        j = (int) (yCentroid + ySD + 1);
        for (i = (int) (xCentroid - xSD - 1); i <= (int) (xCentroid + xSD + 1); i++)
          dNoiseSD += Math.pow(dNoiseAvrg - ipRaw.getPixel(i, j), 2);
        i = (int) (xCentroid - xSD - 1);
        for (j = (int) (yCentroid - ySD); j <= (int) (yCentroid + ySD); j++)
          dNoiseSD += Math.pow(dNoiseAvrg - ipRaw.getPixel(i, j), 2);
        i = (int) (xCentroid + xSD + 1);
        for (j = (int) (yCentroid - ySD); j <= (int) (yCentroid + ySD); j++)
          dNoiseSD += Math.pow(dNoiseAvrg - ipRaw.getPixel(i, j), 2);
        dNoiseSD = Math.sqrt(dNoiseSD / (4 * xSD + 4 * ySD + 8));
        if (nFalsePositive == 1) dSNR = fitted_parameters[1] / dNoiseSD;
        else dSNR = (dIMax - dIMin) / dNoiseSD;
      }
      // }
      if (fitted_parameters[2] > 0
          && fitted_parameters[2] < width
          && fitted_parameters[3] > 0
          && fitted_parameters[3] < height
          && fitted_parameters[1] > 0) {
        if (!(fdg.bIgnoreFP && nFalsePositive > 0.3)) {
          ptable_lock.lock();
          ptable.incrementCounter();

          ptable.addValue("X_(px)", fitted_parameters[2] + 0.5);
          ptable.addValue("Y_(px)", fitted_parameters[3] + 0.5);
          ptable.addValue("Frame_Number", nFrame + 1);
          ptable.addValue("X_(nm)", (fitted_parameters[2] + 0.5) * fdg.dPixelSize);
          ptable.addValue("X_loc_error(nm)", fit_errors[2] * fdg.dPixelSize);
          ptable.addValue("Y_(nm)", (fitted_parameters[3] + 0.5) * fdg.dPixelSize);
          ptable.addValue("Y_loc_error(nm)", fit_errors[3] * fdg.dPixelSize);
          ptable.addValue("Z_(nm)", 0);
          ptable.addValue("Z_loc_error(nm)", 0);
          ptable.addValue("Amplitude_fit", fitted_parameters[1]);
          ptable.addValue("Amp_error", fit_errors[1]);
          ptable.addValue("BGfit", fitted_parameters[0]);
          ptable.addValue("BGfit_error", fit_errors[0]);
          ptable.addValue("SD_X_(nm)", Math.abs(fitted_parameters[4]) * fdg.dPixelSize);
          ptable.addValue("SD_X_error(nm)", fit_errors[4] * fdg.dPixelSize);
          ptable.addValue("SD_Y_(nm)", Math.abs(fitted_parameters[5]) * fdg.dPixelSize);
          ptable.addValue("SD_Y_error(nm)", fit_errors[5] * fdg.dPixelSize);
          ptable.addValue("False_positive", nFalsePositive);
          ptable.addValue("IntegratedInt", dIntAmp);
          ptable.addValue("SNR", dSNR);
          // ptable.addValue("chi2_fit",chi2_fit);
          ptable.addValue("R2_fit", (1 - (chi2_fit / dIntDev)));
          // ptable.addValue("Iterations_fit",fdg.nIterations);
          ptable.addValue("Iterations_fit", SMLlma.iteration_count);

          // case of importing from MTrackJ
          // keeping track information
          if (particles_.length == 5) {
            ptable.addValue("Track_ID", particles_[2][nParticlesCount]);
            ptable.addValue("Particle_ID", particles_[3][nParticlesCount]);
            ptable.addValue("Track_Length", particles_[4][nParticlesCount]);
          }

          ptable_lock.unlock();
          if (fdg.bShowParticles) {
            spotROI =
                new OvalRoi(
                    xCentroid - 2 * fdg.dPSFsigma,
                    yCentroid - 2 * fdg.dPSFsigma,
                    4.0 * fdg.dPSFsigma,
                    4.0 * fdg.dPSFsigma);
            if (nFalsePositive < 0.5) spotROI.setStrokeColor(Color.green);
            else if (nFalsePositive < 1) spotROI.setStrokeColor(Color.yellow);
            else spotROI.setStrokeColor(Color.red);

            spotROI.setPosition(nFrame + 1);
            SpotsPositions__.add(spotROI);
          }
        }
      }
    } // particles iteration
    // for(nParticlesCount=0;nParticlesCount<nParticlesNumber;nParticlesCount++)

  }
Example #21
0
  void labelParticles(
      ImageProcessor ipBinary,
      ImageProcessor ipRaw,
      int nFrame,
      double dPixelSize_,
      int nAreaCut,
      double dPSFsigma_,
      Overlay SpotsPositions__,
      boolean bShow,
      Roi RoiAct) {
    int width = ipBinary.getWidth();
    int height = ipBinary.getHeight();

    int dBorder; // radius in pixels around center point to fit Gaussian

    int nArea;

    int i, j;

    double dVal, dInt;
    double dIMax, dIMin;

    double xCentroid, yCentroid;
    boolean bBorder;
    boolean bInRoi;

    int lab = 1;
    int[] pos;

    Stack<int[]> sstack = new Stack<int[]>();
    int[][] label = new int[width][height];

    OvalRoi spotROI;

    dBorder = (int) (dPSFsigma_ * DOMConstants.FITRADIUS);

    for (int r = 1; r < width - 1; r++)
      for (int c = 1; c < height - 1; c++) {

        if (ipBinary.getPixel(r, c) == 0.0) continue;
        if (label[r][c] > 0.0) continue;
        /* encountered unlabeled foreground pixel at position r, c */
        /* it means it is a new spot! */
        /* push the position in the stack and assign label */
        sstack.push(new int[] {r, c});
        label[r][c] = lab;
        nArea = 0;
        dIMax = -1000;
        xCentroid = 0;
        yCentroid = 0;
        // xMax = 0; yMax = 0;
        dInt = 0;
        bBorder = false;

        /* start the float fill */
        while (!sstack.isEmpty()) {
          pos = (int[]) sstack.pop();
          i = pos[0];
          j = pos[1];

          // remove all spots at border
          if (i == 0 || j == 0 || i == (width - 1) || j == (height - 1)) bBorder = true;
          nArea++;
          dVal = ipRaw.getPixel(i, j);
          if (dVal > dIMax) dIMax = dVal;
          dInt += dVal;
          xCentroid += dVal * i;
          yCentroid += dVal * j;

          if (ipBinary.getPixel(i - 1, j - 1) > 0 && label[i - 1][j - 1] == 0) {
            sstack.push(new int[] {i - 1, j - 1});
            label[i - 1][j - 1] = lab;
          }

          if (ipBinary.getPixel(i - 1, j) > 0 && label[i - 1][j] == 0) {
            sstack.push(new int[] {i - 1, j});
            label[i - 1][j] = lab;
          }

          if (ipBinary.getPixel(i - 1, j + 1) > 0 && label[i - 1][j + 1] == 0) {
            sstack.push(new int[] {i - 1, j + 1});
            label[i - 1][j + 1] = lab;
          }

          if (ipBinary.getPixel(i, j - 1) > 0 && label[i][j - 1] == 0) {
            sstack.push(new int[] {i, j - 1});
            label[i][j - 1] = lab;
          }

          if (ipBinary.getPixel(i, j + 1) > 0 && label[i][j + 1] == 0) {
            sstack.push(new int[] {i, j + 1});
            label[i][j + 1] = lab;
          }
          if (ipBinary.getPixel(i + 1, j - 1) > 0 && label[i + 1][j - 1] == 0) {
            sstack.push(new int[] {i + 1, j - 1});
            label[i + 1][j - 1] = lab;
          }

          if (ipBinary.getPixel(i + 1, j) > 0 && label[i + 1][j] == 0) {
            sstack.push(new int[] {i + 1, j});
            label[i + 1][j] = lab;
          }

          if (ipBinary.getPixel(i + 1, j + 1) > 0 && label[i + 1][j + 1] == 0) {
            sstack.push(new int[] {i + 1, j + 1});
            label[i + 1][j + 1] = lab;
          }
        } /* end while */
        if (!bBorder && nArea > nAreaCut) {
          xCentroid /= dInt;
          yCentroid /= dInt;

          if ((xCentroid > dBorder)
              && (yCentroid > dBorder)
              && (xCentroid < (width - 1 - dBorder))
              && (yCentroid < (height - 1 - dBorder))) {
            bInRoi = true;
            if (RoiAct != null) {
              if (!RoiAct.contains((int) xCentroid, (int) yCentroid)) bInRoi = false;
            }
            if (bInRoi) {
              // find minimum value around peak position
              dIMin = 1000000;
              // nCount = 0;
              for (i = (int) (Math.round(xCentroid) - dBorder);
                  i <= Math.round(xCentroid) + dBorder;
                  i++)
                for (j = (int) (Math.round(yCentroid) - dBorder);
                    j <= Math.round(yCentroid) + dBorder;
                    j++) {
                  dVal = ipRaw.getPixel(i, j);
                  if (dVal < dIMin) dIMin = dVal;
                }

              ptable_lock.lock();
              ptable.incrementCounter();
              ptable.addValue("Frame Number", nFrame + 1);
              ptable.addValue("X_centroid_(px)", xCentroid);
              ptable.addValue("Y_centroid_(px)", yCentroid);
              ptable.addValue("MaxInt", dIMax);
              ptable.addValue("MinInt", dIMin);

              ptable_lock.unlock();
              if (bShow) {
                spotROI =
                    new OvalRoi(
                        0.5 + xCentroid - 2 * dPSFsigma_,
                        0.5 + yCentroid - 2 * dPSFsigma_,
                        4.0 * dPSFsigma_,
                        4.0 * dPSFsigma_);
                spotROI.setStrokeColor(Color.yellow);
                spotROI.setPosition(nFrame + 1);
                SpotsPositions__.add(spotROI);
              }
            }
          }
        }
        lab++;
      } // end for cycle

    return; // label ;
  }
 int getColumnID(String name) {
   int id = rt.getFreeColumn(name);
   if (id == ResultsTable.COLUMN_IN_USE) id = rt.getColumnIndex(name);
   return id;
 }
  /** Displays a modal options dialog. */
  public boolean showDialog() {
    Calibration cal = imp != null ? imp.getCalibration() : (new Calibration());
    double unitSquared = cal.pixelWidth * cal.pixelHeight;
    if (pixelUnits) unitSquared = 1.0;
    if (Macro.getOptions() != null) {
      boolean oldMacro = updateMacroOptions();
      if (oldMacro) unitSquared = 1.0;
      staticMinSize = 0.0;
      staticMaxSize = DEFAULT_MAX_SIZE;
      staticMinCircularity = 0.0;
      staticMaxCircularity = 1.0;
      staticShowChoice = NOTHING;
    }
    GenericDialog gd = new GenericDialog("Analyze Particles");
    minSize = staticMinSize;
    maxSize = staticMaxSize;
    minCircularity = staticMinCircularity;
    maxCircularity = staticMaxCircularity;
    showChoice = staticShowChoice;
    if (maxSize == 999999) maxSize = DEFAULT_MAX_SIZE;
    options = staticOptions;
    String unit = cal.getUnit();
    boolean scaled = cal.scaled();
    if (unit.equals("inch")) {
      unit = "pixel";
      unitSquared = 1.0;
      scaled = false;
      pixelUnits = true;
    }
    String units = unit + "^2";
    int places = 0;
    double cmin = minSize * unitSquared;
    if ((int) cmin != cmin) places = 2;
    double cmax = maxSize * unitSquared;
    if ((int) cmax != cmax && cmax != DEFAULT_MAX_SIZE) places = 2;
    String minStr = ResultsTable.d2s(cmin, places);
    if (minStr.indexOf("-") != -1) {
      for (int i = places; i <= 6; i++) {
        minStr = ResultsTable.d2s(cmin, i);
        if (minStr.indexOf("-") == -1) break;
      }
    }
    String maxStr = ResultsTable.d2s(cmax, places);
    if (maxStr.indexOf("-") != -1) {
      for (int i = places; i <= 6; i++) {
        maxStr = ResultsTable.d2s(cmax, i);
        if (maxStr.indexOf("-") == -1) break;
      }
    }
    if (scaled) gd.setInsets(5, 0, 0);
    gd.addStringField("Size (" + units + "):", minStr + "-" + maxStr, 12);
    if (scaled) {
      gd.setInsets(0, 40, 5);
      gd.addCheckbox("Pixel units", pixelUnits);
    }
    gd.addStringField("Circularity:", IJ.d2s(minCircularity) + "-" + IJ.d2s(maxCircularity), 12);
    gd.addChoice("Show:", showStrings, showStrings[showChoice]);
    String[] labels = new String[8];
    boolean[] states = new boolean[8];
    labels[0] = "Display results";
    states[0] = (options & SHOW_RESULTS) != 0;
    labels[1] = "Exclude on edges";
    states[1] = (options & EXCLUDE_EDGE_PARTICLES) != 0;
    labels[2] = "Clear results";
    states[2] = (options & CLEAR_WORKSHEET) != 0;
    labels[3] = "Include holes";
    states[3] = (options & INCLUDE_HOLES) != 0;
    labels[4] = "Summarize";
    states[4] = (options & DISPLAY_SUMMARY) != 0;
    labels[5] = "Record starts";
    states[5] = (options & RECORD_STARTS) != 0;
    labels[6] = "Add to Manager";
    states[6] = (options & ADD_TO_MANAGER) != 0;
    labels[7] = "In_situ Show";
    states[7] = (options & IN_SITU_SHOW) != 0;
    gd.addCheckboxGroup(4, 2, labels, states);
    gd.addHelp(IJ.URL + "/docs/menus/analyze.html#ap");
    gd.showDialog();
    if (gd.wasCanceled()) return false;

    String size = gd.getNextString(); // min-max size
    if (scaled) pixelUnits = gd.getNextBoolean();
    if (pixelUnits) unitSquared = 1.0;
    else unitSquared = cal.pixelWidth * cal.pixelHeight;
    String[] minAndMax = Tools.split(size, " -");
    double mins = gd.parseDouble(minAndMax[0]);
    double maxs = minAndMax.length == 2 ? gd.parseDouble(minAndMax[1]) : Double.NaN;
    minSize = Double.isNaN(mins) ? DEFAULT_MIN_SIZE : mins / unitSquared;
    maxSize = Double.isNaN(maxs) ? DEFAULT_MAX_SIZE : maxs / unitSquared;
    if (minSize < DEFAULT_MIN_SIZE) minSize = DEFAULT_MIN_SIZE;
    if (maxSize < minSize) maxSize = DEFAULT_MAX_SIZE;
    staticMinSize = minSize;
    staticMaxSize = maxSize;

    minAndMax = Tools.split(gd.getNextString(), " -"); // min-max circularity
    double minc = gd.parseDouble(minAndMax[0]);
    double maxc = minAndMax.length == 2 ? gd.parseDouble(minAndMax[1]) : Double.NaN;
    minCircularity = Double.isNaN(minc) ? 0.0 : minc;
    maxCircularity = Double.isNaN(maxc) ? 1.0 : maxc;
    if (minCircularity < 0.0 || minCircularity > 1.0) minCircularity = 0.0;
    if (maxCircularity < minCircularity || maxCircularity > 1.0) maxCircularity = 1.0;
    if (minCircularity == 1.0 && maxCircularity == 1.0) minCircularity = 0.0;
    staticMinCircularity = minCircularity;
    staticMaxCircularity = maxCircularity;

    if (gd.invalidNumber()) {
      IJ.error("Bins invalid.");
      canceled = true;
      return false;
    }
    showChoice = gd.getNextChoiceIndex();
    staticShowChoice = showChoice;
    if (gd.getNextBoolean()) options |= SHOW_RESULTS;
    else options &= ~SHOW_RESULTS;
    if (gd.getNextBoolean()) options |= EXCLUDE_EDGE_PARTICLES;
    else options &= ~EXCLUDE_EDGE_PARTICLES;
    if (gd.getNextBoolean()) options |= CLEAR_WORKSHEET;
    else options &= ~CLEAR_WORKSHEET;
    if (gd.getNextBoolean()) options |= INCLUDE_HOLES;
    else options &= ~INCLUDE_HOLES;
    if (gd.getNextBoolean()) options |= DISPLAY_SUMMARY;
    else options &= ~DISPLAY_SUMMARY;
    if (gd.getNextBoolean()) options |= RECORD_STARTS;
    else options &= ~RECORD_STARTS;
    if (gd.getNextBoolean()) options |= ADD_TO_MANAGER;
    else options &= ~ADD_TO_MANAGER;
    if (gd.getNextBoolean()) options |= IN_SITU_SHOW;
    else options &= ~IN_SITU_SHOW;
    staticOptions = options;
    options |= SHOW_PROGRESS;
    if ((options & DISPLAY_SUMMARY) != 0)
      Analyzer.setMeasurements(Analyzer.getMeasurements() | AREA);
    return true;
  }
 String n(double n) {
   String s;
   if (Math.round(n) == n) s = ResultsTable.d2s(n, 0);
   else s = ResultsTable.d2s(n, Analyzer.getPrecision());
   return "\t" + s;
 }
Example #25
0
 // default constructor
 SMLAnalysis() {
   ptable = ResultsTable.getResultsTable();
   ptable.setPrecision(5);
 }
  /**
   * Performs particle analysis on the specified ImagePlus and ImageProcessor. Returns false if
   * there is an error.
   */
  public boolean analyze(ImagePlus imp, ImageProcessor ip) {
    if (this.imp == null) this.imp = imp;
    showResults = (options & SHOW_RESULTS) != 0;
    excludeEdgeParticles = (options & EXCLUDE_EDGE_PARTICLES) != 0;
    resetCounter = (options & CLEAR_WORKSHEET) != 0;
    showProgress = (options & SHOW_PROGRESS) != 0;
    floodFill = (options & INCLUDE_HOLES) == 0;
    recordStarts = (options & RECORD_STARTS) != 0;
    addToManager = (options & ADD_TO_MANAGER) != 0;
    displaySummary = (options & DISPLAY_SUMMARY) != 0;
    inSituShow = (options & IN_SITU_SHOW) != 0;
    outputImage = null;
    ip.snapshot();
    ip.setProgressBar(null);
    if (Analyzer.isRedirectImage()) {
      redirectImp = Analyzer.getRedirectImage(imp);
      if (redirectImp == null) return false;
      int depth = redirectImp.getStackSize();
      if (depth > 1 && depth == imp.getStackSize()) {
        ImageStack redirectStack = redirectImp.getStack();
        redirectIP = redirectStack.getProcessor(imp.getCurrentSlice());
      } else redirectIP = redirectImp.getProcessor();
    } else if (imp.getType() == ImagePlus.COLOR_RGB) {
      ImagePlus original = (ImagePlus) imp.getProperty("OriginalImage");
      if (original != null
          && original.getWidth() == imp.getWidth()
          && original.getHeight() == imp.getHeight()) {
        redirectImp = original;
        redirectIP = original.getProcessor();
      }
    }
    if (!setThresholdLevels(imp, ip)) return false;
    width = ip.getWidth();
    height = ip.getHeight();
    if (!(showChoice == NOTHING || showChoice == OVERLAY_OUTLINES || showChoice == OVERLAY_MASKS)) {
      blackBackground = Prefs.blackBackground && inSituShow;
      if (slice == 1) outlines = new ImageStack(width, height);
      if (showChoice == ROI_MASKS) drawIP = new ShortProcessor(width, height);
      else drawIP = new ByteProcessor(width, height);
      drawIP.setLineWidth(lineWidth);
      if (showChoice == ROI_MASKS) {
      } // Place holder for now...
      else if (showChoice == MASKS && !blackBackground) drawIP.invertLut();
      else if (showChoice == OUTLINES) {
        if (!inSituShow) {
          if (customLut == null) makeCustomLut();
          drawIP.setColorModel(customLut);
        }
        drawIP.setFont(new Font("SansSerif", Font.PLAIN, fontSize));
        if (fontSize > 12 && inSituShow) drawIP.setAntialiasedText(true);
      }
      outlines.addSlice(null, drawIP);

      if (showChoice == ROI_MASKS || blackBackground) {
        drawIP.setColor(Color.black);
        drawIP.fill();
        drawIP.setColor(Color.white);
      } else {
        drawIP.setColor(Color.white);
        drawIP.fill();
        drawIP.setColor(Color.black);
      }
    }
    calibration = redirectImp != null ? redirectImp.getCalibration() : imp.getCalibration();

    if (rt == null) {
      rt = Analyzer.getResultsTable();
      analyzer = new Analyzer(imp);
    } else analyzer = new Analyzer(imp, measurements, rt);
    if (resetCounter && slice == 1) {
      if (!Analyzer.resetCounter()) return false;
    }
    beginningCount = Analyzer.getCounter();

    byte[] pixels = null;
    if (ip instanceof ByteProcessor) pixels = (byte[]) ip.getPixels();
    if (r == null) {
      r = ip.getRoi();
      mask = ip.getMask();
      if (displaySummary) {
        if (mask != null) totalArea = ImageStatistics.getStatistics(ip, AREA, calibration).area;
        else totalArea = r.width * calibration.pixelWidth * r.height * calibration.pixelHeight;
      }
    }
    minX = r.x;
    maxX = r.x + r.width;
    minY = r.y;
    maxY = r.y + r.height;
    if (r.width < width || r.height < height || mask != null) {
      if (!eraseOutsideRoi(ip, r, mask)) return false;
    }
    int offset;
    double value;
    int inc = Math.max(r.height / 25, 1);
    int mi = 0;
    ImageWindow win = imp.getWindow();
    if (win != null) win.running = true;
    if (measurements == 0) measurements = Analyzer.getMeasurements();
    if (showChoice == ELLIPSES) measurements |= ELLIPSE;
    measurements &= ~LIMIT; // ignore "Limit to Threshold"
    roiNeedsImage =
        (measurements & PERIMETER) != 0
            || (measurements & SHAPE_DESCRIPTORS) != 0
            || (measurements & FERET) != 0;
    particleCount = 0;
    wand = new Wand(ip);
    pf = new PolygonFiller();
    if (floodFill) {
      ImageProcessor ipf = ip.duplicate();
      ipf.setValue(fillColor);
      ff = new FloodFiller(ipf);
    }
    roiType = Wand.allPoints() ? Roi.FREEROI : Roi.TRACED_ROI;

    for (int y = r.y; y < (r.y + r.height); y++) {
      offset = y * width;
      for (int x = r.x; x < (r.x + r.width); x++) {
        if (pixels != null) value = pixels[offset + x] & 255;
        else if (imageType == SHORT) value = ip.getPixel(x, y);
        else value = ip.getPixelValue(x, y);
        if (value >= level1 && value <= level2) analyzeParticle(x, y, imp, ip);
      }
      if (showProgress && ((y % inc) == 0)) IJ.showProgress((double) (y - r.y) / r.height);
      if (win != null) canceled = !win.running;
      if (canceled) {
        Macro.abort();
        break;
      }
    }
    if (showProgress) IJ.showProgress(1.0);
    if (showResults) rt.updateResults();
    imp.killRoi();
    ip.resetRoi();
    ip.reset();
    if (displaySummary && IJ.getInstance() != null) updateSliceSummary();
    if (addToManager && roiManager != null) roiManager.setEditMode(imp, true);
    maxParticleCount = (particleCount > maxParticleCount) ? particleCount : maxParticleCount;
    totalCount += particleCount;
    if (!canceled) showResults();
    return true;
  }