Beispiel #1
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));
 }
 private void getintbright() {
   weights = new float[ncurves][xpts][ypts];
   for (int i = 0; i < ncurves; i++) {
     nmeas[i] = 0;
     for (int j = 0; j < xpts; j++) {
       for (int k = 0; k < ypts; k++) {
         nmeas[i] += (int) pch[i][j][k];
       }
     }
     double tempavg = 0.0;
     double tempavg2 = 0.0;
     double temp2avg = 0.0;
     double temp2avg2 = 0.0;
     double tempccavg = 0.0;
     for (int j = 0; j < xpts; j++) {
       for (int k = 0; k < ypts; k++) {
         double normed = (double) pch[i][j][k] / (double) nmeas[i];
         if (pch[i][j][k] > 0.0f) {
           weights[i][j][k] = (float) ((double) nmeas[i] / (normed * (1.0f - normed)));
         } else {
           weights[i][j][k] = 1.0f;
         }
         tempavg += normed * (double) j;
         tempavg2 += normed * (double) j * (double) j;
         temp2avg += normed * (double) k;
         temp2avg2 += normed * (double) k * (double) k;
         tempccavg += normed * (double) k * (double) j;
       }
     }
     tempccavg -= tempavg * temp2avg;
     brightcc[i] = tempccavg / Math.sqrt(tempavg * temp2avg);
     tempavg2 -= tempavg * tempavg;
     tempavg2 /= tempavg;
     bright1[i] = (tempavg2 - 1.0);
     temp2avg2 -= temp2avg * temp2avg;
     temp2avg2 /= temp2avg;
     bright2[i] = (temp2avg2 - 1.0);
     intensity1[i] = tempavg;
     intensity2[i] = temp2avg;
     if (psfflag == 0) {
       bright1[i] /= 0.3536;
       bright2[i] /= 0.3536;
       brightcc[i] /= 0.3536;
     } else {
       if (psfflag == 1) {
         bright1[i] /= 0.078;
         bright2[i] /= 0.078;
         brightcc[i] /= 0.078;
       } else {
         bright1[i] /= 0.5;
         bright2[i] /= 0.5;
         brightcc[i] /= 0.5;
       }
     }
     number1[i] = intensity1[i] / bright1[i];
     number2[i] = intensity2[i] / bright2[i];
     brightmincc[i] = (bright1[i] * beta) * Math.sqrt(intensity1[i] / intensity2[i]);
   }
 }
Beispiel #3
0
 double rodbard(double x) {
   // y = c*((a-x/(x-d))^(1/b)
   // a=3.9, b=.88, c=712, d=44
   double ex;
   if (x == 0.0) ex = 5.0;
   else ex = Math.exp(Math.log(x / 700.0) * 0.88);
   double y = 3.9 - 44.0;
   y = y / (1.0 + ex);
   return y + 44.0;
 }
Beispiel #4
0
 int[] smooth(int[] a, int n) {
   FloatProcessor fp = new FloatProcessor(n, 1);
   for (int i = 0; i < n; i++) fp.putPixelValue(i, 0, a[i]);
   GaussianBlur gb = new GaussianBlur();
   gb.blur1Direction(fp, 2.0, 0.01, true, 0);
   for (int i = 0; i < n; i++) a[i] = (int) Math.round(fp.getPixelValue(i, 0));
   return a;
 }
  void Contrast(ImagePlus imp, int radius, double par1, double par2, boolean doIwhite) {
    // G. Landini, 2013
    // Based on a simple contrast toggle. This procedure does not have user-provided paramters other
    // than the kernel radius
    // Sets the pixel value to either white or black depending on whether its current value is
    // closest to the local Max or Min respectively
    // The procedure is similar to Toggle Contrast Enhancement (see Soille, Morphological Image
    // Analysis (2004), p. 259

    ImagePlus Maximp, Minimp;
    ImageProcessor ip = imp.getProcessor(), ipMax, ipMin;
    int c_value = 0;
    int mid_gray;
    byte object;
    byte backg;

    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++) {
      pixels[i] =
          ((Math.abs((int) (max[i] & 0xff - pixels[i] & 0xff))
                  <= Math.abs((int) (pixels[i] & 0xff - min[i] & 0xff))))
              ? object
              : backg;
    }
    // imp.updateAndDraw();
    return;
  }
  /*------------------------------------------------------------------*/
  double getInitialCausalCoefficientMirrorOnBounds(double[] c, double z, double tolerance) {
    double z1 = z, zn = Math.pow(z, c.length - 1);
    double sum = c[0] + zn * c[c.length - 1];
    int horizon = c.length;

    if (0.0 < tolerance) {
      horizon = 2 + (int) (Math.log(tolerance) / Math.log(Math.abs(z)));
      horizon = (horizon < c.length) ? (horizon) : (c.length);
    }
    zn = zn * zn;
    for (int n = 1; (n < (horizon - 1)); n++) {
      zn = zn / z;
      sum = sum + (z1 + zn) * c[n];
      z1 = z1 * z;
    }
    return (sum / (1.0 - Math.pow(z, 2 * c.length - 2)));
  } /* end getInitialCausalCoefficientMirrorOnBounds */
Beispiel #7
0
 public void drop(DropTargetDropEvent dtde) {
   dtde.acceptDrop(DnDConstants.ACTION_COPY);
   DataFlavor[] flavors = null;
   try {
     Transferable t = dtde.getTransferable();
     iterator = null;
     flavors = t.getTransferDataFlavors();
     if (IJ.debugMode) IJ.log("DragAndDrop.drop: " + flavors.length + " flavors");
     for (int i = 0; i < flavors.length; i++) {
       if (IJ.debugMode) IJ.log("  flavor[" + i + "]: " + flavors[i].getMimeType());
       if (flavors[i].isFlavorJavaFileListType()) {
         Object data = t.getTransferData(DataFlavor.javaFileListFlavor);
         iterator = ((List) data).iterator();
         break;
       } else if (flavors[i].isFlavorTextType()) {
         Object ob = t.getTransferData(flavors[i]);
         if (!(ob instanceof String)) continue;
         String s = ob.toString().trim();
         if (IJ.isLinux() && s.length() > 1 && (int) s.charAt(1) == 0) s = fixLinuxString(s);
         ArrayList list = new ArrayList();
         if (s.indexOf("href=\"") != -1 || s.indexOf("src=\"") != -1) {
           s = parseHTML(s);
           if (IJ.debugMode) IJ.log("  url: " + s);
           list.add(s);
           this.iterator = list.iterator();
           break;
         }
         BufferedReader br = new BufferedReader(new StringReader(s));
         String tmp;
         while (null != (tmp = br.readLine())) {
           tmp = java.net.URLDecoder.decode(tmp.replaceAll("\\+", "%2b"), "UTF-8");
           if (tmp.startsWith("file://")) tmp = tmp.substring(7);
           if (IJ.debugMode) IJ.log("  content: " + tmp);
           if (tmp.startsWith("http://")) list.add(s);
           else list.add(new File(tmp));
         }
         this.iterator = list.iterator();
         break;
       }
     }
     if (iterator != null) {
       Thread thread = new Thread(this, "DrawAndDrop");
       thread.setPriority(Math.max(thread.getPriority() - 1, Thread.MIN_PRIORITY));
       thread.start();
     }
   } catch (Exception e) {
     dtde.dropComplete(false);
     return;
   }
   dtde.dropComplete(true);
   if (flavors == null || flavors.length == 0) {
     if (IJ.isMacOSX())
       IJ.error(
           "First drag and drop ignored. Please try again. You can avoid this\n"
               + "problem by dragging to the toolbar instead of the status bar.");
     else IJ.error("Drag and drop failed");
   }
 }
Beispiel #8
0
 PolygonRoi trimPolygon(PolygonRoi roi, double length) {
   int[] x = roi.getXCoordinates();
   int[] y = roi.getYCoordinates();
   int n = roi.getNCoordinates();
   x = smooth(x, n);
   y = smooth(y, n);
   float[] curvature = getCurvature(x, y, n);
   Rectangle r = roi.getBounds();
   double threshold = rodbard(length);
   // IJ.log("trim: "+length+" "+threshold);
   double distance = Math.sqrt((x[1] - x[0]) * (x[1] - x[0]) + (y[1] - y[0]) * (y[1] - y[0]));
   x[0] += r.x;
   y[0] += r.y;
   int i2 = 1;
   int x1, y1, x2 = 0, y2 = 0;
   for (int i = 1; i < n - 1; i++) {
     x1 = x[i];
     y1 = y[i];
     x2 = x[i + 1];
     y2 = y[i + 1];
     distance += Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1)) + 1;
     distance += curvature[i] * 2;
     if (distance >= threshold) {
       x[i2] = x2 + r.x;
       y[i2] = y2 + r.y;
       i2++;
       distance = 0.0;
     }
   }
   int type = roi.getType() == Roi.FREELINE ? Roi.POLYLINE : Roi.POLYGON;
   if (type == Roi.POLYLINE && distance > 0.0) {
     x[i2] = x2 + r.x;
     y[i2] = y2 + r.y;
     i2++;
   }
   PolygonRoi p = new PolygonRoi(x, y, i2, type);
   if (roi.getStroke() != null) p.setStrokeWidth(roi.getStrokeWidth());
   p.setStrokeColor(roi.getStrokeColor());
   p.setName(roi.getName());
   imp.setRoi(p);
   return p;
 }
Beispiel #9
0
 public void postProcess() {
   double stdDev;
   double n = num;
   for (int i = 0; i < len; i++) {
     if (num > 1) {
       stdDev = (n * sum2[i] - sum[i] * sum[i]) / n;
       if (stdDev > 0.0) result[i] = (float) Math.sqrt(stdDev / (n - 1.0));
       else result[i] = 0f;
     } else result[i] = 0f;
   }
 }
Beispiel #10
0
  public void run(String arg) {
    int[] wList = WindowManager.getIDList();
    if (wList == null) {
      IJ.error("No images are open.");
      return;
    }

    double thalf = 0.5;
    boolean keep;

    GenericDialog gd = new GenericDialog("Bleach correction");

    gd.addNumericField("t½:", thalf, 1);
    gd.addCheckbox("Keep source stack:", true);
    gd.showDialog();
    if (gd.wasCanceled()) return;

    long start = System.currentTimeMillis();
    thalf = gd.getNextNumber();
    keep = gd.getNextBoolean();
    if (keep) IJ.run("Duplicate...", "title='Bleach corrected' duplicate");
    ImagePlus imp1 = WindowManager.getCurrentImage();
    int d1 = imp1.getStackSize();
    double v1, v2;
    int width = imp1.getWidth();
    int height = imp1.getHeight();
    ImageProcessor ip1, ip2, ip3;

    int slices = imp1.getStackSize();
    ImageStack stack1 = imp1.getStack();
    ImageStack stack2 = imp1.getStack();
    int currentSlice = imp1.getCurrentSlice();

    for (int n = 1; n <= slices; n++) {
      ip1 = stack1.getProcessor(n);
      ip3 = stack1.getProcessor(1);
      ip2 = stack2.getProcessor(n);
      for (int x = 0; x < width; x++) {
        for (int y = 0; y < height; y++) {
          v1 = ip1.getPixelValue(x, y);
          v2 = ip3.getPixelValue(x, y);

          // =B8/(EXP(-C$7*A8))
          v1 = (v1 / Math.exp(-n * thalf));
          ip2.putPixelValue(x, y, v1);
        }
      }
      IJ.showProgress((double) n / slices);
      IJ.showStatus(n + "/" + slices);
    }

    // stack2.show();
    imp1.updateAndDraw();
  }
Beispiel #11
0
 PolygonRoi trimFloatPolygon(PolygonRoi roi, double length) {
   FloatPolygon poly = roi.getFloatPolygon();
   float[] x = poly.xpoints;
   float[] y = poly.ypoints;
   int n = poly.npoints;
   x = smooth(x, n);
   y = smooth(y, n);
   float[] curvature = getCurvature(x, y, n);
   double threshold = rodbard(length);
   // IJ.log("trim: "+length+" "+threshold);
   double distance = Math.sqrt((x[1] - x[0]) * (x[1] - x[0]) + (y[1] - y[0]) * (y[1] - y[0]));
   int i2 = 1;
   double x1, y1, x2 = 0, y2 = 0;
   for (int i = 1; i < n - 1; i++) {
     x1 = x[i];
     y1 = y[i];
     x2 = x[i + 1];
     y2 = y[i + 1];
     distance += Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1)) + 1;
     distance += curvature[i] * 2;
     if (distance >= threshold) {
       x[i2] = (float) x2;
       y[i2] = (float) y2;
       i2++;
       distance = 0.0;
     }
   }
   int type = roi.getType() == Roi.FREELINE ? Roi.POLYLINE : Roi.POLYGON;
   if (type == Roi.POLYLINE && distance > 0.0) {
     x[i2] = (float) x2;
     y[i2] = (float) y2;
     i2++;
   }
   PolygonRoi p = new PolygonRoi(x, y, i2, type);
   if (roi.getStroke() != null) p.setStrokeWidth(roi.getStrokeWidth());
   p.setStrokeColor(roi.getStrokeColor());
   p.setDrawOffset(roi.getDrawOffset());
   p.setName(roi.getName());
   imp.setRoi(p);
   return p;
 }
 /* Extracts indexes of first and last indexes of stim imp that match response imp*/
 private int[] getFirstNLast(ImagePlus imp, String userInput) {
   String stackTitle = "Substack (" + userInput + ")";
   if (stackTitle.length() > 25) {
     int idxA = stackTitle.indexOf(",", 18);
     int idxB = stackTitle.lastIndexOf(",");
     if (idxA >= 1 && idxB >= 1) {
       String strA = stackTitle.substring(0, idxA);
       String strB = stackTitle.substring(idxB + 1);
       stackTitle = strA + ", ... " + strB;
     }
   }
   int[] out = new int[2];
   try {
     int idx1 = userInput.indexOf("-");
     if (idx1 >= 1) { // input displayed in range
       String rngStart = userInput.substring(0, idx1);
       String rngEnd = userInput.substring(idx1 + 1);
       Integer obj = new Integer(rngStart);
       int first = 1 + (obj.intValue() - 1) * Math.round((float) (this.dt_r / this.DT_S));
       int inc = 1;
       int idx2 = rngEnd.indexOf("-");
       if (idx2 >= 1) {
         String rngEndAndInc = rngEnd;
         rngEnd = rngEndAndInc.substring(0, idx2);
         String rngInc = rngEndAndInc.substring(idx2 + 1);
         obj = new Integer(rngInc);
         inc = 1 + (obj.intValue() - 1) * Math.round((float) (this.dt_r / this.DT_S));
       }
       obj = new Integer(rngEnd);
       int last = (obj.intValue()) * Math.round((float) (this.dt_r / this.DT_S));
       out[0] = first;
       out[1] = last;
     } else {
       throw new Exception();
     }
   } catch (Exception e) {
     IJ.error("Substack Maker", "Invalid input string:        \n \n  \"" + userInput + "\"");
   }
   return out;
 }
Beispiel #13
0
 void addSelection() {
   ImagePlus imp = IJ.getImage();
   String macroOptions = Macro.getOptions();
   if (macroOptions != null && IJ.macroRunning() && macroOptions.indexOf("remove") != -1) {
     imp.setOverlay(null);
     return;
   }
   Roi roi = imp.getRoi();
   if (roi == null && imp.getOverlay() != null) {
     GenericDialog gd = new GenericDialog("No Selection");
     gd.addMessage("\"Overlay>Add\" requires a selection.");
     gd.setInsets(15, 40, 0);
     gd.addCheckbox("Remove existing overlay", false);
     gd.showDialog();
     if (gd.wasCanceled()) return;
     if (gd.getNextBoolean()) imp.setOverlay(null);
     return;
   }
   if (roi == null) {
     IJ.error("This command requires a selection.");
     return;
   }
   roi = (Roi) roi.clone();
   if (roi.getStrokeColor() == null) roi.setStrokeColor(Toolbar.getForegroundColor());
   int width = Line.getWidth();
   Rectangle bounds = roi.getBounds();
   boolean tooWide = width > Math.max(bounds.width, bounds.height) / 3.0;
   if (roi.getStroke() == null && width > 1 && !tooWide) roi.setStrokeWidth(Line.getWidth());
   Overlay overlay = imp.getOverlay();
   if (overlay != null && overlay.size() > 0 && !roi.isDrawingTool()) {
     Roi roi2 = overlay.get(overlay.size() - 1);
     if (roi.getStroke() == null) roi.setStrokeWidth(roi2.getStrokeWidth());
     if (roi.getFillColor() == null) roi.setFillColor(roi2.getFillColor());
   }
   boolean points = roi instanceof PointRoi && ((PolygonRoi) roi).getNCoordinates() > 1;
   if (points) roi.setStrokeColor(Color.red);
   if (!IJ.altKeyDown() && !(roi instanceof Arrow)) {
     RoiProperties rp = new RoiProperties("Add to Overlay", roi);
     if (!rp.showDialog()) return;
   }
   String name = roi.getName();
   boolean newOverlay = name != null && name.equals("new-overlay");
   if (overlay == null || newOverlay) overlay = new Overlay();
   overlay.add(roi);
   imp.setOverlay(overlay);
   overlay2 = overlay;
   if (points || (roi instanceof ImageRoi) || (roi instanceof Arrow)) imp.killRoi();
   Undo.setup(Undo.OVERLAY_ADDITION, imp);
 }
Beispiel #14
0
 float[] getCurvature(float[] x, float[] y, int n) {
   float[] x2 = new float[n];
   float[] y2 = new float[n];
   for (int i = 0; i < n; i++) {
     x2[i] = x[i];
     y2[i] = y[i];
   }
   ImageProcessor ipx = new FloatProcessor(n, 1, x, null);
   ImageProcessor ipy = new FloatProcessor(n, 1, y, null);
   ipx.convolve(kernel, kernel.length, 1);
   ipy.convolve(kernel, kernel.length, 1);
   float[] indexes = new float[n];
   float[] curvature = new float[n];
   for (int i = 0; i < n; i++) {
     indexes[i] = i;
     curvature[i] =
         (float) Math.sqrt((x2[i] - x[i]) * (x2[i] - x[i]) + (y2[i] - y[i]) * (y2[i] - y[i]));
   }
   return curvature;
 }
Beispiel #15
0
  /*------------------------------------------------------------------*/
  void getSplineInterpolationCoefficients(double[] c, double tolerance) {
    double z[] = {Math.sqrt(3.0) - 2.0};
    double lambda = 1.0;

    if (c.length == 1) {
      return;
    }
    for (int k = 0; (k < z.length); k++) {
      lambda = lambda * (1.0 - z[k]) * (1.0 - 1.0 / z[k]);
    }
    for (int n = 0; (n < c.length); n++) {
      c[n] = c[n] * lambda;
    }
    for (int k = 0; (k < z.length); k++) {
      c[0] = getInitialCausalCoefficientMirrorOnBounds(c, z[k], tolerance);
      for (int n = 1; (n < c.length); n++) {
        c[n] = c[n] + z[k] * c[n - 1];
      }
      c[c.length - 1] = getInitialAntiCausalCoefficientMirrorOnBounds(c, z[k], tolerance);
      for (int n = c.length - 2; (0 <= n); n--) {
        c[n] = z[k] * (c[n + 1] - c[n]);
      }
    }
  } /* end getSplineInterpolationCoefficients */
Beispiel #16
0
  public boolean dialogItemChanged(GenericDialog gd, AWTEvent e) {
    int width = imp.getWidth();
    int height = imp.getHeight();
    type = gd.getNextChoice();
    areaPerPoint = gd.getNextNumber();
    color = gd.getNextChoice();
    randomOffset = gd.getNextBoolean();

    double minArea = (width * height) / 50000.0;
    if (type.equals(types[1]) && minArea < 144.0) minArea = 144.0;
    else if (minArea < 16) minArea = 16.0;
    if (areaPerPoint / (pixelWidth * pixelHeight) < minArea) {
      String err = "\"Area per Point\" too small";
      if (gd.wasOKed()) IJ.error("Grid", err);
      else IJ.showStatus(err);
      return true;
    }
    double tileSize = Math.sqrt(areaPerPoint);
    tileWidth = tileSize / pixelWidth;
    tileHeight = tileSize / pixelHeight;
    if (randomOffset) {
      xstart = (int) (random.nextDouble() * tileWidth);
      ystart = (int) (random.nextDouble() * tileHeight);
    } else {
      xstart = (int) (tileWidth / 2.0 + 0.5);
      ystart = (int) (tileHeight / 2.0 + 0.5);
    }
    linesV = (int) ((width - xstart) / tileWidth) + 1;
    linesH = (int) ((height - ystart) / tileHeight) + 1;
    if (gd.invalidNumber()) return true;
    if (type.equals(types[0])) drawLines();
    else if (type.equals(types[1])) drawCrosses();
    else if (type.equals(types[2])) drawPoints();
    else showGrid(null);
    return true;
  }
Beispiel #17
0
 ImagePlus doMedianProjection() {
   IJ.showStatus("Calculating median...");
   ImageStack stack = imp.getStack();
   ImageProcessor[] slices = new ImageProcessor[sliceCount];
   int index = 0;
   for (int slice = startSlice; slice <= stopSlice; slice += increment)
     slices[index++] = stack.getProcessor(slice);
   ImageProcessor ip2 = slices[0].duplicate();
   ip2 = ip2.convertToFloat();
   float[] values = new float[sliceCount];
   int width = ip2.getWidth();
   int height = ip2.getHeight();
   int inc = Math.max(height / 30, 1);
   for (int y = 0; y < height; y++) {
     if (y % inc == 0) IJ.showProgress(y, height - 1);
     for (int x = 0; x < width; x++) {
       for (int i = 0; i < sliceCount; i++) values[i] = slices[i].getPixelValue(x, y);
       ip2.putPixelValue(x, y, median(values));
     }
   }
   if (imp.getBitDepth() == 8) ip2 = ip2.convertToByte(false);
   IJ.showProgress(1, 1);
   return new ImagePlus(makeTitle(), ip2);
 }
Beispiel #18
0
  /*
  if selection is closed shape, create a circle with the same area and centroid, otherwise use<br>
  the Pratt method to fit a circle to the points that define the line or multi-point selection.<br>
  Reference: Pratt V., Direct least-squares fitting of algebraic surfaces", Computer Graphics, Vol. 21, pages 145-152 (1987).<br>
  Original code: Nikolai Chernov's MATLAB script for Newton-based Pratt fit.<br>
  (http://www.math.uab.edu/~chernov/cl/MATLABcircle.html)<br>
  Java version: https://github.com/mdoube/BoneJ/blob/master/src/org/doube/geometry/FitCircle.java<br>
  @authors Nikolai Chernov, Michael Doube, Ved Sharma
  */
  void fitCircle(ImagePlus imp) {
    Roi roi = imp.getRoi();
    if (roi == null) {
      noRoi("Fit Circle");
      return;
    }

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

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

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

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

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

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

    // calculate the circle parameters
    double DET = xnew * xnew - xnew * Mz + Cov_xy;
    double CenterX = (Mxz * (Myy - xnew) - Myz * Mxy) / (2 * DET);
    double CenterY = (Myz * (Mxx - xnew) - Mxz * Mxy) / (2 * DET);
    double radius = Math.sqrt(CenterX * CenterX + CenterY * CenterY + Mz + 2 * xnew);
    if (Double.isNaN(radius)) {
      IJ.error("Fit Circle", "Points are collinear.");
      return;
    }
    CenterX = CenterX + meanx;
    CenterY = CenterY + meany;
    imp.killRoi();
    IJ.makeOval(
        (int) Math.round(CenterX - radius),
        (int) Math.round(CenterY - radius),
        (int) Math.round(2 * radius),
        (int) Math.round(2 * radius));
  }
Beispiel #19
0
  private boolean track(
      ImagePlus siPlus, ArrayList<Point2D.Double> xyPoints, ArrayList<Double> timePoints) {

    GaussianFit gs = new GaussianFit(shape_, fitMode_);

    double cPCF = photonConversionFactor_ / gain_;

    // for now, take the active ImageJ image
    // (this should be an image of a difraction limited spot)

    Roi originalRoi = siPlus.getRoi();
    if (null == originalRoi) {
      if (!silent_) IJ.error("Please draw a Roi around the spot you want to track");
      return false;
    }

    Polygon pol = FindLocalMaxima.FindMax(siPlus, halfSize_, noiseTolerance_, preFilterType_);
    if (pol.npoints == 0) {
      if (!silent_) ReportingUtils.showError("No local maxima found in ROI");
      else ReportingUtils.logError("No local maxima found in ROI");
      return false;
    }

    int xc = pol.xpoints[0];
    int yc = pol.ypoints[0];
    // not sure if needed, but look for the maximum local maximum
    int max = siPlus.getProcessor().getPixel(pol.xpoints[0], pol.ypoints[0]);
    if (pol.npoints > 1) {
      for (int i = 1; i < pol.npoints; i++) {
        if (siPlus.getProcessor().getPixel(pol.xpoints[i], pol.ypoints[i]) > max) {
          max = siPlus.getProcessor().getPixel(pol.xpoints[i], pol.ypoints[i]);
          xc = pol.xpoints[i];
          yc = pol.ypoints[i];
        }
      }
    }

    long startTime = System.nanoTime();

    // This is confusing.   We like to accomodate stacks with multiple slices
    // and stacks with multiple frames (which is actually the correct way

    int ch = siPlus.getChannel();
    Boolean useSlices = siPlus.getNSlices() > siPlus.getNFrames();

    int n = siPlus.getSlice();
    int nMax = siPlus.getNSlices();
    if (!useSlices) {
      n = siPlus.getFrame();
      nMax = siPlus.getNFrames();
    }
    boolean stop = false;
    int missedFrames = 0;
    int size = 2 * halfSize_;

    for (int i = n; i <= nMax && !stop; i++) {
      SpotData spot;

      // Give user feedback
      ij.IJ.showStatus("Tracking...");
      ij.IJ.showProgress(i, nMax);

      // Search in next slice in same Roi for local maximum
      Roi searchRoi = new Roi(xc - size, yc - size, 2 * size + 1, 2 * size + 1);
      if (useSlices) {
        siPlus.setSliceWithoutUpdate(siPlus.getStackIndex(ch, i, 1));
      } else {
        siPlus.setSliceWithoutUpdate(siPlus.getStackIndex(ch, 1, i));
      }
      siPlus.setRoi(searchRoi, false);

      // Find maximum in Roi, might not be needed....
      pol = FindLocalMaxima.FindMax(siPlus, 2 * halfSize_, noiseTolerance_, preFilterType_);

      // do not stray more than 2 pixels in x or y.
      // This velocity maximum parameter should be tunable by the user
      if (pol.npoints >= 1) {
        if (Math.abs(xc - pol.xpoints[0]) < 2 && Math.abs(yc - pol.ypoints[0]) < 2) {
          xc = pol.xpoints[0];
          yc = pol.ypoints[0];
        }
      }

      // Reset ROI to the original
      if (i == n) {
        firstX_ = xc;
        firstY_ = yc;
      }

      // Set Roi for fitting centered around maximum
      Roi spotRoi = new Roi(xc - halfSize_, yc - halfSize_, 2 * halfSize_, 2 * halfSize_);
      siPlus.setRoi(spotRoi, false);
      ImageProcessor ip;
      try {
        if (siPlus.getRoi() != spotRoi) {
          ReportingUtils.logError(
              "There seems to be a thread synchronization issue going on that causes this weirdness");
        }
        ip = siPlus.getProcessor().crop();
      } catch (ArrayIndexOutOfBoundsException aex) {
        ReportingUtils.logError(aex, "ImageJ failed to crop the image, not sure why");
        siPlus.setRoi(spotRoi, true);
        ip = siPlus.getProcessor().crop();
      }

      spot = new SpotData(ip, ch, 1, i, 1, i, xc, yc);
      double[] paramsOut = gs.dogaussianfit(ip, maxIterations_);
      double sx;
      double sy;
      double a = 1.0;
      double theta = 0.0;
      if (paramsOut.length >= 4) {
        // anormalize the intensity from the Gaussian fit
        double N =
            cPCF
                * paramsOut[GaussianFit.INT]
                * (2 * Math.PI * paramsOut[GaussianFit.S] * paramsOut[GaussianFit.S]);
        double xpc = paramsOut[GaussianFit.XC];
        double ypc = paramsOut[GaussianFit.YC];
        double x = (xpc - halfSize_ + xc) * pixelSize_;
        double y = (ypc - halfSize_ + yc) * pixelSize_;

        double s = paramsOut[GaussianFit.S] * pixelSize_;
        // express background in photons after base level correction
        double bgr = cPCF * (paramsOut[GaussianFit.BGR] - baseLevel_);
        // calculate error using formular from Thompson et al (2002)
        // (dx)2 = (s*s + (a*a/12)) / N + (8*pi*s*s*s*s * b*b) / (a*a*N*N)
        double sigma =
            (s * s + (pixelSize_ * pixelSize_) / 12) / N
                + (8 * Math.PI * s * s * s * s * bgr * bgr) / (pixelSize_ * pixelSize_ * N * N);
        sigma = Math.sqrt(sigma);

        double width = 2 * s;
        if (paramsOut.length >= 6) {
          sx = paramsOut[GaussianFit.S1] * pixelSize_;
          sy = paramsOut[GaussianFit.S2] * pixelSize_;
          a = sx / sy;
        }

        if (paramsOut.length >= 7) {
          theta = paramsOut[GaussianFit.S3];
        }
        if ((!useWidthFilter_ || (width > widthMin_ && width < widthMax_))
            && (!useNrPhotonsFilter_ || (N > nrPhotonsMin_ && N < nrPhotonsMax_))) {
          // If we have a good fit, update position of the box
          if (xpc > 0 && xpc < (2 * halfSize_) && ypc > 0 && ypc < (2 * halfSize_)) {
            xc += (int) xpc - halfSize_;
            yc += (int) ypc - halfSize_;
          }
          spot.setData(N, bgr, x, y, 0.0, 2 * s, a, theta, sigma);
          xyPoints.add(new Point2D.Double(x, y));
          timePoints.add(i * timeIntervalMs_);
          resultList_.add(spot);
          missedFrames = 0;
        } else {
          missedFrames += 1;
        }
      } else {
        missedFrames += 1;
      }
      if (endTrackAfterBadFrames_) {
        if (missedFrames >= this.endTrackAfterNBadFrames_) {
          stop = true;
        }
      }
    }

    long endTime = System.nanoTime();
    double took = (endTime - startTime) / 1E6;

    print("Calculation took: " + took + " milli seconds");

    ij.IJ.showStatus("");

    siPlus.setSlice(n);
    siPlus.setRoi(originalRoi);

    return true;
  }
  void Sauvola(ImagePlus imp, int radius, double par1, double par2, boolean doIwhite) {
    // Sauvola recommends K_VALUE = 0.5 and R_VALUE = 128.
    // This is a modification of Niblack's thresholding method.
    // Sauvola J. and Pietaksinen M. (2000) "Adaptive Document Image Binarization"
    // Pattern Recognition, 33(2): 225-236
    // http://www.ee.oulu.fi/mvg/publications/show_pdf.php?ID=24
    // 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 Meanimp, Varimp;
    ImageProcessor ip = imp.getProcessor(), ipMean, ipVar;
    double k_value = 0.5;
    double r_value = 128;
    byte object;
    byte backg;

    if (par1 != 0) {
      IJ.log("Sauvola: changed k_value from :" + k_value + "  to:" + par1);
      k_value = par1;
    }

    if (par2 != 0) {
      IJ.log("Sauvola: changed r_value from :" + r_value + "  to:" + par2);
      r_value = par2;
    }

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

    Meanimp = duplicateImage(ip);
    ImageConverter ic = new ImageConverter(Meanimp);
    ic.convertToGray32();

    ipMean = Meanimp.getProcessor();
    RankFilters rf = new RankFilters();
    rf.rank(ipMean, radius, rf.MEAN); // Mean
    // Meanimp.show();
    Varimp = duplicateImage(ip);
    ic = new ImageConverter(Varimp);
    ic.convertToGray32();
    ipVar = Varimp.getProcessor();
    rf.rank(ipVar, radius, rf.VARIANCE); // Variance
    // Varimp.show();
    byte[] pixels = (byte[]) ip.getPixels();
    float[] mean = (float[]) ipMean.getPixels();
    float[] var = (float[]) ipVar.getPixels();

    for (int i = 0; i < pixels.length; i++)
      pixels[i] =
          ((int) (pixels[i] & 0xff)
                  > (int) (mean[i] * (1.0 + k_value * ((Math.sqrt(var[i]) / r_value) - 1.0))))
              ? object
              : backg;
    // imp.updateAndDraw();
    return;
  }
Beispiel #21
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;
 }
 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;
 }
  /**
   * 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;
  }
 public boolean get_errors(double[] params, int[] fixes) {
   GenericDialog gd = new GenericDialog("Error Options");
   String[] methods = {"Support Plane", "Monte Carlo"};
   gd.addChoice("Method", methods, methods[0]);
   float conf = 0.67f;
   gd.addNumericField("SP_Confidence Limit (%)", (int) (conf * 100.0f), 5, 10, null);
   String[] labels = {"P1", "P2", "P3", "P4", "P5", "P6", "P7", "P8", "P9", "P10"};
   gd.addChoice("SP_Parameter", labels, labels[0]);
   double spacing = 0.01;
   gd.addNumericField("SP_Chi^2_plot_spacing (% of value)?", spacing * 100.0, 2, 10, null);
   int ntrials = 100;
   gd.addNumericField("MC_#_Trials", ntrials, 0);
   gd.showDialog();
   if (gd.wasCanceled()) {
     return false;
   }
   int methodindex = gd.getNextChoiceIndex();
   conf = 0.01f * (float) gd.getNextNumber();
   int paramindex = gd.getNextChoiceIndex();
   spacing = 0.01 * gd.getNextNumber();
   ntrials = (int) gd.getNextNumber();
   if (methodindex == 0) {
     support_plane_errors_v2 erclass = new support_plane_errors_v2(this, 0.0001, 50, false, 0.1);
     int errindex = paramindex;
     int nfit = 0;
     for (int i = 0; i < labels.length; i++) {
       if (fixes[i] == 0) {
         nfit++;
       }
     }
     int npts = tempdata.length;
     int dofnum = npts - (nfit - 1) - 1;
     int dofden = npts - nfit - 1;
     double flim = (new jdist()).FLimit(dofnum, dofden, (double) conf);
     IJ.log("FLimit = " + (float) flim);
     if (flim == Double.NaN && flim < 1.0) {
       IJ.showMessage("Invalid Limiting F Value");
       return false;
     }
     double truespacing = Math.abs(params[errindex] * spacing);
     double[][] c2plot =
         erclass.geterrors(
             params, fixes, constraints, tempdata, weights, flim, truespacing, errindex);
     IJ.log("upper limit = " + c2plot[1][0] + " lower limit = " + c2plot[0][0]);
     IJ.log(
         "upper error = "
             + (c2plot[1][0] - params[errindex])
             + " lower error = "
             + (params[errindex] - c2plot[0][0]));
     int templength = c2plot[0].length;
     float[][] c2plotf = new float[2][templength - 1];
     for (int i = 0; i < (templength - 1); i++) {
       c2plotf[0][i] = (float) c2plot[0][i + 1];
       c2plotf[1][i] = (float) c2plot[1][i + 1];
     }
     new PlotWindow4("c2 plot", labels[errindex], "Chi^2", c2plotf[0], c2plotf[1]).draw();
   } else {
     StringBuffer sb = new StringBuffer();
     sb.append("Trial\t");
     for (int i = 0; i < labels.length; i++) {
       if (fixes[i] == 0) sb.append(labels[i] + "\t");
     }
     sb.append("chi^2");
     tw = new TextWindow("Monte Carlo Results", sb.toString(), "", 400, 400);
     redirect = true;
     monte_carlo_errors_v2 erclass = new monte_carlo_errors_v2(this, 0.0001, 50, false, 0.1);
     double[][] errors = erclass.geterrors(params, fixes, constraints, tempdata, weights, ntrials);
     sb = new StringBuffer();
     sb.append("StDev\t");
     for (int i = 0; i < errors.length; i++) {
       float[] ferr = new float[errors[0].length];
       for (int j = 0; j < ferr.length; j++) ferr[j] = (float) errors[i][j];
       float stdev = jstatistics.getstatistic("StDev", ferr, null);
       sb.append("" + stdev);
       if (i < (errors.length - 1)) sb.append("\t");
     }
     tw.append(sb.toString());
     redirect = false;
   }
   return true;
 }
Beispiel #25
0
	public void run(String arg) {

  int[] wList = WindowManager.getIDList();
        if (wList==null) {
            IJ.error("No images are open.");
            return;
        }
	double kernel=3;
	double kernelsum = 0;
	double kernelvarsum =0;
	double kernalvar = 0;
	double sigmawidth = 2;
	int kernelindex, minpixnumber;
	String[] kernelsize =  { "3�,"5�, "7�, "9�};

	GenericDialog gd = new GenericDialog("Sigma Filter");
	gd.addChoice("Kernel size", kernelsize, kernelsize[0]);
	gd.addNumericField("Sigma width",sigmawidth , 2);
	gd.addNumericField("Minimum number of pixels", 1, 0);

	gd.addCheckbox("Keep source:",true);
	gd.addCheckbox("Do all stack:",true);
	gd.addCheckbox("Modified Lee's FIlter:",true);
	       	
	gd.showDialog();
       	if (gd.wasCanceled()) return ;
	kernelindex =  gd.getNextChoiceIndex();
          	sigmawidth = gd.getNextNumber();
          	minpixnumber = ((int)gd.getNextNumber());
          	boolean keep = gd.getNextBoolean();
	boolean doallstack = gd.getNextBoolean();
	boolean modified = gd.getNextBoolean();
	if (kernelindex==0) kernel = 3;
	if (kernelindex==1) kernel = 5;
	if (kernelindex==2) kernel = 7;
	if (kernelindex==3) kernel = 9;
    	long start = System.currentTimeMillis();
	
if (minpixnumber> (kernel*kernel)){
	      IJ.showMessage("Sigma filter", "There must be more pixels in the kernel than+\n" + "the minimum number to be included");
            return;
        }
	double v, midintensity;
	int   x, y, ix, iy;
	double sum = 0;
	double backupsum =0;
	int count = 0;
	int n = 0;
	if (keep) {IJ.run("Select All"); IJ.run("Duplicate...", "title='Sigma filtered' duplicate");}

	int radius = (int)(kernel-1)/2;
	ImagePlus imp = WindowManager.getCurrentImage();
	ImageStack stack1 = imp.getStack();
	int width = imp.getWidth();
	int height = imp.getHeight();
	int nslices = stack1.getSize();
	int cslice = imp.getCurrentSlice();
	double status = width*height*nslices;
	
	ImageProcessor  ip = imp.getProcessor();
	int sstart = 1;
	if (!doallstack) {sstart = cslice; nslices=sstart;status = status/nslices;};

 for (int i=sstart; i<=nslices; i++) {
                imp.setSlice(i);
                    
for (x=radius;x<width+radius;x++)	{
		for (y=radius;y<height+radius;y++)	{
			
			midintensity = ip.getPixelValue(x,y);
			count = 0;
			sum = 0;
			kernelsum =0;
			kernalvar =0;
			kernelvarsum =0;
			backupsum = 0;

		//calculate mean of kernel value
			for (ix=0;ix<kernel;ix++)	{
					for (iy=0;iy<kernel;iy++)	{
							v = ip.getPixelValue(x+ix-radius,y+iy-radius);
							kernelsum = kernelsum+v;
								}
						}
			double sigmacalcmean = (kernelsum/(kernel*kernel));

		//calculate variance of kernel
			for (ix=0;ix<kernel;ix++)	{
					for (iy=0;iy<kernel;iy++)	{
							v = ip.getPixelValue(x+ix-radius,y+iy-radius);
							kernalvar = (v-sigmacalcmean)*(v-sigmacalcmean);
							kernelvarsum = kernelvarsum + kernalvar;
								}
						}
			//double variance = kernelvarsum/kernel;
			double sigmacalcvar = kernelvarsum/((kernel*kernel)-1);

			//calcuate sigma range = sqrt(variance/(mean^2)) � sigmawidth
			double sigmarange  = sigmawidth*(Math.sqrt((sigmacalcvar) /(sigmacalcmean*sigmacalcmean)));
			//calulate sigma top value and bottom value
			double sigmatop = midintensity*(1+sigmarange);
			double sigmabottom = midintensity*(1-sigmarange);
			//calculate mean of values that differ are in sigma range.
			for (ix=0;ix<kernel;ix++)	{
					for (iy=0;iy<kernel;iy++)	{
							v = ip.getPixelValue(x+ix-radius,y+iy-radius);
							if ((v>=sigmabottom)&&(v<=sigmatop)){
								sum = sum+v;
								count = count+1;   }
								backupsum = v+ backupsum;
										}		
						}
//if there are too few pixels in the kernal that are within sigma range, the 
//mean of the entire kernal is taken. My modification of Lee's filter is to exclude the central value 
//from the calculation of the mean as I assume it to be spuriously high or low 
			if (!(count>(minpixnumber)))
				{sum = (backupsum-midintensity);
				count = (int)((kernel*kernel)-1);
				if (!modified)
					{sum = (backupsum);
					count  = (int)(kernel*kernel);}
				}
			
			double val =  (sum/count);
			ip.putPixelValue(x,y, val);
			n = n+1;
	double percentage = (((double)n/status)*100);
			 IJ.showStatus(IJ.d2s(percentage,0) +"% done");		
			
}

	//		IJ.showProgress(i, status);
					}}
			imp.updateAndDraw();
 			IJ.showStatus(IJ.d2s((System.currentTimeMillis()-start)/1000.0, 2)+" seconds");        }      
Beispiel #26
0
  String getInfo(ImagePlus imp, ImageProcessor ip) {
    String s = new String("\n");
    s += "Title: " + imp.getTitle() + "\n";
    Calibration cal = imp.getCalibration();
    int stackSize = imp.getStackSize();
    int channels = imp.getNChannels();
    int slices = imp.getNSlices();
    int frames = imp.getNFrames();
    int digits = imp.getBitDepth() == 32 ? 4 : 0;
    if (cal.scaled()) {
      String unit = cal.getUnit();
      String units = cal.getUnits();
      s +=
          "Width:  "
              + IJ.d2s(imp.getWidth() * cal.pixelWidth, 2)
              + " "
              + units
              + " ("
              + imp.getWidth()
              + ")\n";
      s +=
          "Height:  "
              + IJ.d2s(imp.getHeight() * cal.pixelHeight, 2)
              + " "
              + units
              + " ("
              + imp.getHeight()
              + ")\n";
      if (slices > 1)
        s += "Depth:  " + IJ.d2s(slices * cal.pixelDepth, 2) + " " + units + " (" + slices + ")\n";
      double xResolution = 1.0 / cal.pixelWidth;
      double yResolution = 1.0 / cal.pixelHeight;
      int places = Tools.getDecimalPlaces(xResolution, yResolution);
      if (xResolution == yResolution)
        s += "Resolution:  " + IJ.d2s(xResolution, places) + " pixels per " + unit + "\n";
      else {
        s += "X Resolution:  " + IJ.d2s(xResolution, places) + " pixels per " + unit + "\n";
        s += "Y Resolution:  " + IJ.d2s(yResolution, places) + " pixels per " + unit + "\n";
      }
    } else {
      s += "Width:  " + imp.getWidth() + " pixels\n";
      s += "Height:  " + imp.getHeight() + " pixels\n";
      if (stackSize > 1) s += "Depth:  " + slices + " pixels\n";
    }
    if (stackSize > 1)
      s +=
          "Voxel size: "
              + d2s(cal.pixelWidth)
              + "x"
              + d2s(cal.pixelHeight)
              + "x"
              + d2s(cal.pixelDepth)
              + " "
              + cal.getUnit()
              + "\n";
    else
      s +=
          "Pixel size: "
              + d2s(cal.pixelWidth)
              + "x"
              + d2s(cal.pixelHeight)
              + " "
              + cal.getUnit()
              + "\n";

    s += "ID: " + imp.getID() + "\n";
    String zOrigin = stackSize > 1 || cal.zOrigin != 0.0 ? "," + d2s(cal.zOrigin) : "";
    s += "Coordinate origin:  " + d2s(cal.xOrigin) + "," + d2s(cal.yOrigin) + zOrigin + "\n";
    int type = imp.getType();
    switch (type) {
      case ImagePlus.GRAY8:
        s += "Bits per pixel: 8 ";
        String lut = "LUT";
        if (imp.getProcessor().isColorLut()) lut = "color " + lut;
        else lut = "grayscale " + lut;
        if (imp.isInvertedLut()) lut = "inverting " + lut;
        s += "(" + lut + ")\n";
        if (imp.getNChannels() > 1) s += displayRanges(imp);
        else s += "Display range: " + (int) ip.getMin() + "-" + (int) ip.getMax() + "\n";
        break;
      case ImagePlus.GRAY16:
      case ImagePlus.GRAY32:
        if (type == ImagePlus.GRAY16) {
          String sign = cal.isSigned16Bit() ? "signed" : "unsigned";
          s += "Bits per pixel: 16 (" + sign + ")\n";
        } else s += "Bits per pixel: 32 (float)\n";
        if (imp.getNChannels() > 1) s += displayRanges(imp);
        else {
          s += "Display range: ";
          double min = ip.getMin();
          double max = ip.getMax();
          if (cal.calibrated()) {
            min = cal.getCValue((int) min);
            max = cal.getCValue((int) max);
          }
          s += IJ.d2s(min, digits) + " - " + IJ.d2s(max, digits) + "\n";
        }
        break;
      case ImagePlus.COLOR_256:
        s += "Bits per pixel: 8 (color LUT)\n";
        break;
      case ImagePlus.COLOR_RGB:
        s += "Bits per pixel: 32 (RGB)\n";
        break;
    }
    double interval = cal.frameInterval;
    double fps = cal.fps;
    if (stackSize > 1) {
      ImageStack stack = imp.getStack();
      int slice = imp.getCurrentSlice();
      String number = slice + "/" + stackSize;
      String label = stack.getShortSliceLabel(slice);
      if (label != null && label.length() > 0) label = " (" + label + ")";
      else label = "";
      if (interval > 0.0 || fps != 0.0) {
        s += "Frame: " + number + label + "\n";
        if (fps != 0.0) {
          String sRate =
              Math.abs(fps - Math.round(fps)) < 0.00001 ? IJ.d2s(fps, 0) : IJ.d2s(fps, 5);
          s += "Frame rate: " + sRate + " fps\n";
        }
        if (interval != 0.0)
          s +=
              "Frame interval: "
                  + ((int) interval == interval ? IJ.d2s(interval, 0) : IJ.d2s(interval, 5))
                  + " "
                  + cal.getTimeUnit()
                  + "\n";
      } else s += "Image: " + number + label + "\n";
      if (imp.isHyperStack()) {
        if (channels > 1) s += "  Channel: " + imp.getChannel() + "/" + channels + "\n";
        if (slices > 1) s += "  Slice: " + imp.getSlice() + "/" + slices + "\n";
        if (frames > 1) s += "  Frame: " + imp.getFrame() + "/" + frames + "\n";
      }
      if (imp.isComposite()) {
        if (!imp.isHyperStack() && channels > 1) s += "  Channels: " + channels + "\n";
        String mode = ((CompositeImage) imp).getModeAsString();
        s += "  Composite mode: \"" + mode + "\"\n";
      }
    }

    if (ip.getMinThreshold() == ImageProcessor.NO_THRESHOLD) s += "No Threshold\n";
    else {
      double lower = ip.getMinThreshold();
      double upper = ip.getMaxThreshold();
      int dp = digits;
      if (cal.calibrated()) {
        lower = cal.getCValue((int) lower);
        upper = cal.getCValue((int) upper);
        dp = cal.isSigned16Bit() ? 0 : 4;
      }
      s += "Threshold: " + IJ.d2s(lower, dp) + "-" + IJ.d2s(upper, dp) + "\n";
    }
    ImageCanvas ic = imp.getCanvas();
    double mag = ic != null ? ic.getMagnification() : 1.0;
    if (mag != 1.0) s += "Magnification: " + IJ.d2s(mag, 2) + "\n";

    if (cal.calibrated()) {
      s += " \n";
      int curveFit = cal.getFunction();
      s += "Calibration Function: ";
      if (curveFit == Calibration.UNCALIBRATED_OD) s += "Uncalibrated OD\n";
      else if (curveFit == Calibration.CUSTOM) s += "Custom lookup table\n";
      else s += CurveFitter.fList[curveFit] + "\n";
      double[] c = cal.getCoefficients();
      if (c != null) {
        s += "  a: " + IJ.d2s(c[0], 6) + "\n";
        s += "  b: " + IJ.d2s(c[1], 6) + "\n";
        if (c.length >= 3) s += "  c: " + IJ.d2s(c[2], 6) + "\n";
        if (c.length >= 4) s += "  c: " + IJ.d2s(c[3], 6) + "\n";
        if (c.length >= 5) s += "  c: " + IJ.d2s(c[4], 6) + "\n";
      }
      s += "  Unit: \"" + cal.getValueUnit() + "\"\n";
    } else s += "Uncalibrated\n";

    FileInfo fi = imp.getOriginalFileInfo();
    if (fi != null) {
      if (fi.url != null && !fi.url.equals("")) s += "URL: " + fi.url + "\n";
      else if (fi.directory != null && fi.fileName != null)
        s += "Path: " + fi.directory + fi.fileName + "\n";
    }

    ImageWindow win = imp.getWindow();
    if (win != null) {
      Point loc = win.getLocation();
      Dimension screen = IJ.getScreenSize();
      s +=
          "Screen location: "
              + loc.x
              + ","
              + loc.y
              + " ("
              + screen.width
              + "x"
              + screen.height
              + ")\n";
    }

    Overlay overlay = imp.getOverlay();
    if (overlay != null) {
      String hidden = imp.getHideOverlay() ? " (hidden)" : " ";
      int n = overlay.size();
      String elements = n == 1 ? " element" : " elements";
      s += "Overlay: " + n + elements + (imp.getHideOverlay() ? " (hidden)" : "") + "\n";
    } else s += "No Overlay\n";

    Roi roi = imp.getRoi();
    if (roi == null) {
      if (cal.calibrated()) s += " \n";
      s += "No Selection\n";
    } else if (roi instanceof EllipseRoi) {
      s += "\nElliptical Selection\n";
      double[] p = ((EllipseRoi) roi).getParams();
      double dx = p[2] - p[0];
      double dy = p[3] - p[1];
      double major = Math.sqrt(dx * dx + dy * dy);
      s += "  Major: " + IJ.d2s(major, 2) + "\n";
      s += "  Minor: " + IJ.d2s(major * p[4], 2) + "\n";
      s += "  X1: " + IJ.d2s(p[0], 2) + "\n";
      s += "  Y1: " + IJ.d2s(p[1], 2) + "\n";
      s += "  X2: " + IJ.d2s(p[2], 2) + "\n";
      s += "  Y2: " + IJ.d2s(p[3], 2) + "\n";
      s += "  Aspect ratio: " + IJ.d2s(p[4], 2) + "\n";
    } else {
      s += " \n";
      s += roi.getTypeAsString() + " Selection";
      String points = null;
      if (roi instanceof PointRoi) {
        int npoints = ((PolygonRoi) roi).getNCoordinates();
        String suffix = npoints > 1 ? "s)" : ")";
        points = " (" + npoints + " point" + suffix;
      }
      String name = roi.getName();
      if (name != null) {
        s += " (\"" + name + "\")";
        if (points != null) s += "\n " + points;
      } else if (points != null) s += points;
      s += "\n";
      Rectangle r = roi.getBounds();
      if (roi instanceof Line) {
        Line line = (Line) roi;
        s += "  X1: " + IJ.d2s(line.x1d * cal.pixelWidth) + "\n";
        s += "  Y1: " + IJ.d2s(yy(line.y1d, imp) * cal.pixelHeight) + "\n";
        s += "  X2: " + IJ.d2s(line.x2d * cal.pixelWidth) + "\n";
        s += "  Y2: " + IJ.d2s(yy(line.y2d, imp) * cal.pixelHeight) + "\n";
      } else if (cal.scaled()) {
        s += "  X: " + IJ.d2s(cal.getX(r.x)) + " (" + r.x + ")\n";
        s += "  Y: " + IJ.d2s(cal.getY(r.y, imp.getHeight())) + " (" + r.y + ")\n";
        s += "  Width: " + IJ.d2s(r.width * cal.pixelWidth) + " (" + r.width + ")\n";
        s += "  Height: " + IJ.d2s(r.height * cal.pixelHeight) + " (" + r.height + ")\n";
      } else {
        s += "  X: " + r.x + "\n";
        s += "  Y: " + yy(r.y, imp) + "\n";
        s += "  Width: " + r.width + "\n";
        s += "  Height: " + r.height + "\n";
      }
    }

    return s;
  }
Beispiel #27
0
 public void updatebeta() {
   for (int i = 0; i <= ncurves; i++) {
     brightmincc[i] = (bright1[i] * beta) / Math.sqrt(intensity1[i] / intensity2[i]);
     eminccarray[i].setText("" + (float) brightmincc[i]);
   }
 }
Beispiel #28
0
 private void updateavg() {
   nmeas[ncurves] = 0;
   avg = new float[xpts][ypts];
   avgweights = new float[xpts][ypts];
   for (int i = 0; i < ncurves; i++) {
     if (include[i]) {
       for (int j = 0; j < xpts; j++) {
         for (int k = 0; k < ypts; k++) {
           avg[j][k] += pch[i][j][k];
           nmeas[ncurves] += (int) pch[i][j][k];
         }
       }
     }
   }
   double tempavg = 0.0;
   double tempavg2 = 0.0;
   double temp2avg = 0.0;
   double temp2avg2 = 0.0;
   double tempccavg = 0.0;
   for (int i = 0; i < xpts; i++) {
     for (int j = 0; j < ypts; j++) {
       double normed = (double) avg[i][j] / (double) nmeas[ncurves];
       avgweights[i][j] = (float) ((double) nmeas[ncurves] / (normed * (1.0f - normed)));
       if (avg[i][j] > 0.0f) {
         avgweights[i][j] = (float) ((double) nmeas[ncurves] / (normed * (1.0f - normed)));
       } else {
         avgweights[i][j] = 1.0f;
       }
       tempavg += (double) i * normed;
       tempavg2 += (double) i * (double) i * normed;
       temp2avg += (double) j * normed;
       temp2avg2 += (double) j * (double) j * normed;
       tempccavg += (double) i * (double) j * normed;
     }
   }
   tempccavg -= tempavg * temp2avg;
   brightcc[ncurves] = tempccavg / Math.sqrt(tempavg * temp2avg);
   tempavg2 -= tempavg * tempavg;
   tempavg2 /= tempavg;
   bright1[ncurves] = (tempavg2 - 1.0);
   temp2avg2 -= temp2avg * temp2avg;
   temp2avg2 /= temp2avg;
   bright2[ncurves] = (temp2avg2 - 1.0);
   intensity1[ncurves] = tempavg;
   intensity2[ncurves] = temp2avg;
   if (psfflag == 0) {
     bright1[ncurves] /= 0.3536;
     bright2[ncurves] /= 0.3536;
     brightcc[ncurves] /= 0.3536;
   } else {
     if (psfflag == 1) {
       bright1[ncurves] /= 0.078;
       bright2[ncurves] /= 0.078;
       brightcc[ncurves] /= 0.078;
     } else {
       bright1[ncurves] /= 0.5;
       bright2[ncurves] /= 0.5;
       brightcc[ncurves] /= 0.5;
     }
   }
   number1[ncurves] = intensity1[ncurves] / bright1[ncurves];
   number2[ncurves] = intensity2[ncurves] / bright2[ncurves];
   brightmincc[ncurves] =
       (bright1[ncurves] * beta) * Math.sqrt(intensity1[ncurves] / intensity2[ncurves]);
 }
  public void build_bricks() {

    ImagePlus imp;
    ImagePlus orgimp;
    ImageStack stack;
    FileInfo finfo;

    if (lvImgTitle.isEmpty()) return;
    orgimp = WindowManager.getImage(lvImgTitle.get(0));
    imp = orgimp;

    finfo = imp.getFileInfo();
    if (finfo == null) return;

    int[] dims = imp.getDimensions();
    int imageW = dims[0];
    int imageH = dims[1];
    int nCh = dims[2];
    int imageD = dims[3];
    int nFrame = dims[4];
    int bdepth = imp.getBitDepth();
    double xspc = finfo.pixelWidth;
    double yspc = finfo.pixelHeight;
    double zspc = finfo.pixelDepth;
    double z_aspect = Math.max(xspc, yspc) / zspc;

    int orgW = imageW;
    int orgH = imageH;
    int orgD = imageD;
    double orgxspc = xspc;
    double orgyspc = yspc;
    double orgzspc = zspc;

    lv = lvImgTitle.size();
    if (filetype == "JPEG") {
      for (int l = 0; l < lv; l++) {
        if (WindowManager.getImage(lvImgTitle.get(l)).getBitDepth() != 8) {
          IJ.error("A SOURCE IMAGE MUST BE 8BIT GLAYSCALE");
          return;
        }
      }
    }

    // calculate levels
    /*		int baseXY = 256;
    		int baseZ = 256;

    		if (z_aspect < 0.5) baseZ = 128;
    		if (z_aspect > 2.0) baseXY = 128;
    		if (z_aspect >= 0.5 && z_aspect < 1.0) baseZ = (int)(baseZ*z_aspect);
    		if (z_aspect > 1.0 && z_aspect <= 2.0) baseXY = (int)(baseXY/z_aspect);

    		IJ.log("Z_aspect: " + z_aspect);
    		IJ.log("BaseXY: " + baseXY);
    		IJ.log("BaseZ: " + baseZ);
    */

    int baseXY = 256;
    int baseZ = 128;
    int dbXY = Math.max(orgW, orgH) / baseXY;
    if (Math.max(orgW, orgH) % baseXY > 0) dbXY *= 2;
    int dbZ = orgD / baseZ;
    if (orgD % baseZ > 0) dbZ *= 2;
    lv = Math.max(log2(dbXY), log2(dbZ)) + 1;

    int ww = orgW;
    int hh = orgH;
    int dd = orgD;
    for (int l = 0; l < lv; l++) {
      int bwnum = ww / baseXY;
      if (ww % baseXY > 0) bwnum++;
      int bhnum = hh / baseXY;
      if (hh % baseXY > 0) bhnum++;
      int bdnum = dd / baseZ;
      if (dd % baseZ > 0) bdnum++;

      if (bwnum % 2 == 0) bwnum++;
      if (bhnum % 2 == 0) bhnum++;
      if (bdnum % 2 == 0) bdnum++;

      int bw = (bwnum <= 1) ? ww : ww / bwnum + 1 + (ww % bwnum > 0 ? 1 : 0);
      int bh = (bhnum <= 1) ? hh : hh / bhnum + 1 + (hh % bhnum > 0 ? 1 : 0);
      int bd = (bdnum <= 1) ? dd : dd / bdnum + 1 + (dd % bdnum > 0 ? 1 : 0);

      bwlist.add(bw);
      bhlist.add(bh);
      bdlist.add(bd);

      IJ.log("LEVEL: " + l);
      IJ.log("  width: " + ww);
      IJ.log("  hight: " + hh);
      IJ.log("  depth: " + dd);
      IJ.log("  bw: " + bw);
      IJ.log("  bh: " + bh);
      IJ.log("  bd: " + bd);

      int xyl2 = Math.max(ww, hh) / baseXY;
      if (Math.max(ww, hh) % baseXY > 0) xyl2 *= 2;
      if (lv - 1 - log2(xyl2) <= l) {
        ww /= 2;
        hh /= 2;
      }
      IJ.log("  xyl2: " + (lv - 1 - log2(xyl2)));

      int zl2 = dd / baseZ;
      if (dd % baseZ > 0) zl2 *= 2;
      if (lv - 1 - log2(zl2) <= l) dd /= 2;
      IJ.log("  zl2: " + (lv - 1 - log2(zl2)));

      if (l < lv - 1) {
        lvImgTitle.add(lvImgTitle.get(0) + "_level" + (l + 1));
        IJ.selectWindow(lvImgTitle.get(0));
        IJ.run(
            "Scale...",
            "x=- y=- z=- width="
                + ww
                + " height="
                + hh
                + " depth="
                + dd
                + " interpolation=Bicubic average process create title="
                + lvImgTitle.get(l + 1));
      }
    }

    for (int l = 0; l < lv; l++) {
      IJ.log(lvImgTitle.get(l));
    }

    Document doc = newXMLDocument();
    Element root = doc.createElement("BRK");
    root.setAttribute("version", "1.0");
    root.setAttribute("nLevel", String.valueOf(lv));
    root.setAttribute("nChannel", String.valueOf(nCh));
    root.setAttribute("nFrame", String.valueOf(nFrame));
    doc.appendChild(root);

    for (int l = 0; l < lv; l++) {
      IJ.showProgress(0.0);

      int[] dims2 = imp.getDimensions();
      IJ.log(
          "W: "
              + String.valueOf(dims2[0])
              + " H: "
              + String.valueOf(dims2[1])
              + " C: "
              + String.valueOf(dims2[2])
              + " D: "
              + String.valueOf(dims2[3])
              + " T: "
              + String.valueOf(dims2[4])
              + " b: "
              + String.valueOf(bdepth));

      bw = bwlist.get(l).intValue();
      bh = bhlist.get(l).intValue();
      bd = bdlist.get(l).intValue();

      boolean force_pow2 = false;
      /*			if(IsPowerOf2(bw) && IsPowerOf2(bh) && IsPowerOf2(bd)) force_pow2 = true;

      			if(force_pow2){
      				//force pow2
      				if(Pow2(bw) > bw) bw = Pow2(bw)/2;
      				if(Pow2(bh) > bh) bh = Pow2(bh)/2;
      				if(Pow2(bd) > bd) bd = Pow2(bd)/2;
      			}

      			if(bw > imageW) bw = (Pow2(imageW) == imageW) ? imageW : Pow2(imageW)/2;
      			if(bh > imageH) bh = (Pow2(imageH) == imageH) ? imageH : Pow2(imageH)/2;
      			if(bd > imageD) bd = (Pow2(imageD) == imageD) ? imageD : Pow2(imageD)/2;

      */
      if (bw > imageW) bw = imageW;
      if (bh > imageH) bh = imageH;
      if (bd > imageD) bd = imageD;

      if (bw <= 1 || bh <= 1 || bd <= 1) break;

      if (filetype == "JPEG" && (bw < 8 || bh < 8)) break;

      Element lvnode = doc.createElement("Level");
      lvnode.setAttribute("lv", String.valueOf(l));
      lvnode.setAttribute("imageW", String.valueOf(imageW));
      lvnode.setAttribute("imageH", String.valueOf(imageH));
      lvnode.setAttribute("imageD", String.valueOf(imageD));
      lvnode.setAttribute("xspc", String.valueOf(xspc));
      lvnode.setAttribute("yspc", String.valueOf(yspc));
      lvnode.setAttribute("zspc", String.valueOf(zspc));
      lvnode.setAttribute("bitDepth", String.valueOf(bdepth));
      root.appendChild(lvnode);

      Element brksnode = doc.createElement("Bricks");
      brksnode.setAttribute("brick_baseW", String.valueOf(bw));
      brksnode.setAttribute("brick_baseH", String.valueOf(bh));
      brksnode.setAttribute("brick_baseD", String.valueOf(bd));
      lvnode.appendChild(brksnode);

      ArrayList<Brick> bricks = new ArrayList<Brick>();
      int mw, mh, md, mw2, mh2, md2;
      double tx0, ty0, tz0, tx1, ty1, tz1;
      double bx0, by0, bz0, bx1, by1, bz1;
      for (int k = 0; k < imageD; k += bd) {
        if (k > 0) k--;
        for (int j = 0; j < imageH; j += bh) {
          if (j > 0) j--;
          for (int i = 0; i < imageW; i += bw) {
            if (i > 0) i--;
            mw = Math.min(bw, imageW - i);
            mh = Math.min(bh, imageH - j);
            md = Math.min(bd, imageD - k);

            if (force_pow2) {
              mw2 = Pow2(mw);
              mh2 = Pow2(mh);
              md2 = Pow2(md);
            } else {
              mw2 = mw;
              mh2 = mh;
              md2 = md;
            }

            if (filetype == "JPEG") {
              if (mw2 < 8) mw2 = 8;
              if (mh2 < 8) mh2 = 8;
            }

            tx0 = i == 0 ? 0.0d : ((mw2 - mw + 0.5d) / mw2);
            ty0 = j == 0 ? 0.0d : ((mh2 - mh + 0.5d) / mh2);
            tz0 = k == 0 ? 0.0d : ((md2 - md + 0.5d) / md2);

            tx1 = 1.0d - 0.5d / mw2;
            if (mw < bw) tx1 = 1.0d;
            if (imageW - i == bw) tx1 = 1.0d;

            ty1 = 1.0d - 0.5d / mh2;
            if (mh < bh) ty1 = 1.0d;
            if (imageH - j == bh) ty1 = 1.0d;

            tz1 = 1.0d - 0.5d / md2;
            if (md < bd) tz1 = 1.0d;
            if (imageD - k == bd) tz1 = 1.0d;

            bx0 = i == 0 ? 0.0d : (i + 0.5d) / (double) imageW;
            by0 = j == 0 ? 0.0d : (j + 0.5d) / (double) imageH;
            bz0 = k == 0 ? 0.0d : (k + 0.5d) / (double) imageD;

            bx1 = Math.min((i + bw - 0.5d) / (double) imageW, 1.0d);
            if (imageW - i == bw) bx1 = 1.0d;

            by1 = Math.min((j + bh - 0.5d) / (double) imageH, 1.0d);
            if (imageH - j == bh) by1 = 1.0d;

            bz1 = Math.min((k + bd - 0.5d) / (double) imageD, 1.0d);
            if (imageD - k == bd) bz1 = 1.0d;

            int x, y, z;
            x = i - (mw2 - mw);
            y = j - (mh2 - mh);
            z = k - (md2 - md);
            bricks.add(
                new Brick(
                    x, y, z, mw2, mh2, md2, 0, 0, tx0, ty0, tz0, tx1, ty1, tz1, bx0, by0, bz0, bx1,
                    by1, bz1));
          }
        }
      }

      Element fsnode = doc.createElement("Files");
      lvnode.appendChild(fsnode);

      stack = imp.getStack();

      int totalbricknum = nFrame * nCh * bricks.size();
      int curbricknum = 0;
      for (int f = 0; f < nFrame; f++) {
        for (int ch = 0; ch < nCh; ch++) {
          int sizelimit = bdsizelimit * 1024 * 1024;
          int bytecount = 0;
          int filecount = 0;
          int pd_bufsize = Math.max(sizelimit, bw * bh * bd * bdepth / 8);
          byte[] packed_data = new byte[pd_bufsize];
          String base_dataname =
              basename
                  + "_Lv"
                  + String.valueOf(l)
                  + "_Ch"
                  + String.valueOf(ch)
                  + "_Fr"
                  + String.valueOf(f);
          String current_dataname = base_dataname + "_data" + filecount;

          Brick b_first = bricks.get(0);
          if (b_first.z_ != 0) IJ.log("warning");
          int st_z = b_first.z_;
          int ed_z = b_first.z_ + b_first.d_;
          LinkedList<ImageProcessor> iplist = new LinkedList<ImageProcessor>();
          for (int s = st_z; s < ed_z; s++)
            iplist.add(stack.getProcessor(imp.getStackIndex(ch + 1, s + 1, f + 1)));

          //					ImagePlus test;
          //					ImageStack tsst;
          //					test = NewImage.createByteImage("test", imageW, imageH, imageD,
          // NewImage.FILL_BLACK);
          //					tsst = test.getStack();
          for (int i = 0; i < bricks.size(); i++) {
            Brick b = bricks.get(i);

            if (ed_z > b.z_ || st_z < b.z_ + b.d_) {
              if (b.z_ > st_z) {
                for (int s = 0; s < b.z_ - st_z; s++) iplist.pollFirst();
                st_z = b.z_;
              } else if (b.z_ < st_z) {
                IJ.log("warning");
                for (int s = st_z - 1; s > b.z_; s--)
                  iplist.addFirst(stack.getProcessor(imp.getStackIndex(ch + 1, s + 1, f + 1)));
                st_z = b.z_;
              }

              if (b.z_ + b.d_ > ed_z) {
                for (int s = ed_z; s < b.z_ + b.d_; s++)
                  iplist.add(stack.getProcessor(imp.getStackIndex(ch + 1, s + 1, f + 1)));
                ed_z = b.z_ + b.d_;
              } else if (b.z_ + b.d_ < ed_z) {
                IJ.log("warning");
                for (int s = 0; s < ed_z - (b.z_ + b.d_); s++) iplist.pollLast();
                ed_z = b.z_ + b.d_;
              }
            } else {
              IJ.log("warning");
              iplist.clear();
              st_z = b.z_;
              ed_z = b.z_ + b.d_;
              for (int s = st_z; s < ed_z; s++)
                iplist.add(stack.getProcessor(imp.getStackIndex(ch + 1, s + 1, f + 1)));
            }

            if (iplist.size() != b.d_) {
              IJ.log("Stack Error");
              return;
            }

            //						int zz = st_z;

            int bsize = 0;
            byte[] bdata = new byte[b.w_ * b.h_ * b.d_ * bdepth / 8];
            Iterator<ImageProcessor> ipite = iplist.iterator();
            while (ipite.hasNext()) {

              //							ImageProcessor tsip = tsst.getProcessor(zz+1);

              ImageProcessor ip = ipite.next();
              ip.setRoi(b.x_, b.y_, b.w_, b.h_);
              if (bdepth == 8) {
                byte[] data = (byte[]) ip.crop().getPixels();
                System.arraycopy(data, 0, bdata, bsize, data.length);
                bsize += data.length;
              } else if (bdepth == 16) {
                ByteBuffer buffer = ByteBuffer.allocate(b.w_ * b.h_ * bdepth / 8);
                buffer.order(ByteOrder.LITTLE_ENDIAN);
                short[] data = (short[]) ip.crop().getPixels();
                for (short e : data) buffer.putShort(e);
                System.arraycopy(buffer.array(), 0, bdata, bsize, buffer.array().length);
                bsize += buffer.array().length;
              } else if (bdepth == 32) {
                ByteBuffer buffer = ByteBuffer.allocate(b.w_ * b.h_ * bdepth / 8);
                buffer.order(ByteOrder.LITTLE_ENDIAN);
                float[] data = (float[]) ip.crop().getPixels();
                for (float e : data) buffer.putFloat(e);
                System.arraycopy(buffer.array(), 0, bdata, bsize, buffer.array().length);
                bsize += buffer.array().length;
              }
            }

            String filename =
                basename
                    + "_Lv"
                    + String.valueOf(l)
                    + "_Ch"
                    + String.valueOf(ch)
                    + "_Fr"
                    + String.valueOf(f)
                    + "_ID"
                    + String.valueOf(i);

            int offset = bytecount;
            int datasize = bdata.length;

            if (filetype == "RAW") {
              int dummy = -1;
              // do nothing
            }
            if (filetype == "JPEG" && bdepth == 8) {
              try {
                DataBufferByte db = new DataBufferByte(bdata, datasize);
                Raster raster = Raster.createPackedRaster(db, b.w_, b.h_ * b.d_, 8, null);
                BufferedImage img =
                    new BufferedImage(b.w_, b.h_ * b.d_, BufferedImage.TYPE_BYTE_GRAY);
                img.setData(raster);
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                ImageOutputStream ios = ImageIO.createImageOutputStream(baos);
                String format = "jpg";
                Iterator<javax.imageio.ImageWriter> iter =
                    ImageIO.getImageWritersByFormatName("jpeg");
                javax.imageio.ImageWriter writer = iter.next();
                ImageWriteParam iwp = writer.getDefaultWriteParam();
                iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
                iwp.setCompressionQuality((float) jpeg_quality * 0.01f);
                writer.setOutput(ios);
                writer.write(null, new IIOImage(img, null, null), iwp);
                // ImageIO.write(img, format, baos);
                bdata = baos.toByteArray();
                datasize = bdata.length;
              } catch (IOException e) {
                e.printStackTrace();
                return;
              }
            }
            if (filetype == "ZLIB") {
              byte[] tmpdata = new byte[b.w_ * b.h_ * b.d_ * bdepth / 8];
              Deflater compresser = new Deflater();
              compresser.setInput(bdata);
              compresser.setLevel(Deflater.DEFAULT_COMPRESSION);
              compresser.setStrategy(Deflater.DEFAULT_STRATEGY);
              compresser.finish();
              datasize = compresser.deflate(tmpdata);
              bdata = tmpdata;
              compresser.end();
            }

            if (bytecount + datasize > sizelimit && bytecount > 0) {
              BufferedOutputStream fis = null;
              try {
                File file = new File(directory + current_dataname);
                fis = new BufferedOutputStream(new FileOutputStream(file));
                fis.write(packed_data, 0, bytecount);
              } catch (IOException e) {
                e.printStackTrace();
                return;
              } finally {
                try {
                  if (fis != null) fis.close();
                } catch (IOException e) {
                  e.printStackTrace();
                  return;
                }
              }
              filecount++;
              current_dataname = base_dataname + "_data" + filecount;
              bytecount = 0;
              offset = 0;
              System.arraycopy(bdata, 0, packed_data, bytecount, datasize);
              bytecount += datasize;
            } else {
              System.arraycopy(bdata, 0, packed_data, bytecount, datasize);
              bytecount += datasize;
            }

            Element filenode = doc.createElement("File");
            filenode.setAttribute("filename", current_dataname);
            filenode.setAttribute("channel", String.valueOf(ch));
            filenode.setAttribute("frame", String.valueOf(f));
            filenode.setAttribute("brickID", String.valueOf(i));
            filenode.setAttribute("offset", String.valueOf(offset));
            filenode.setAttribute("datasize", String.valueOf(datasize));
            filenode.setAttribute("filetype", String.valueOf(filetype));

            fsnode.appendChild(filenode);

            curbricknum++;
            IJ.showProgress((double) (curbricknum) / (double) (totalbricknum));
          }
          if (bytecount > 0) {
            BufferedOutputStream fis = null;
            try {
              File file = new File(directory + current_dataname);
              fis = new BufferedOutputStream(new FileOutputStream(file));
              fis.write(packed_data, 0, bytecount);
            } catch (IOException e) {
              e.printStackTrace();
              return;
            } finally {
              try {
                if (fis != null) fis.close();
              } catch (IOException e) {
                e.printStackTrace();
                return;
              }
            }
          }
        }
      }

      for (int i = 0; i < bricks.size(); i++) {
        Brick b = bricks.get(i);
        Element bricknode = doc.createElement("Brick");
        bricknode.setAttribute("id", String.valueOf(i));
        bricknode.setAttribute("st_x", String.valueOf(b.x_));
        bricknode.setAttribute("st_y", String.valueOf(b.y_));
        bricknode.setAttribute("st_z", String.valueOf(b.z_));
        bricknode.setAttribute("width", String.valueOf(b.w_));
        bricknode.setAttribute("height", String.valueOf(b.h_));
        bricknode.setAttribute("depth", String.valueOf(b.d_));
        brksnode.appendChild(bricknode);

        Element tboxnode = doc.createElement("tbox");
        tboxnode.setAttribute("x0", String.valueOf(b.tx0_));
        tboxnode.setAttribute("y0", String.valueOf(b.ty0_));
        tboxnode.setAttribute("z0", String.valueOf(b.tz0_));
        tboxnode.setAttribute("x1", String.valueOf(b.tx1_));
        tboxnode.setAttribute("y1", String.valueOf(b.ty1_));
        tboxnode.setAttribute("z1", String.valueOf(b.tz1_));
        bricknode.appendChild(tboxnode);

        Element bboxnode = doc.createElement("bbox");
        bboxnode.setAttribute("x0", String.valueOf(b.bx0_));
        bboxnode.setAttribute("y0", String.valueOf(b.by0_));
        bboxnode.setAttribute("z0", String.valueOf(b.bz0_));
        bboxnode.setAttribute("x1", String.valueOf(b.bx1_));
        bboxnode.setAttribute("y1", String.valueOf(b.by1_));
        bboxnode.setAttribute("z1", String.valueOf(b.bz1_));
        bricknode.appendChild(bboxnode);
      }

      if (l < lv - 1) {
        imp = WindowManager.getImage(lvImgTitle.get(l + 1));
        int[] newdims = imp.getDimensions();
        imageW = newdims[0];
        imageH = newdims[1];
        imageD = newdims[3];
        xspc = orgxspc * ((double) orgW / (double) imageW);
        yspc = orgyspc * ((double) orgH / (double) imageH);
        zspc = orgzspc * ((double) orgD / (double) imageD);
        bdepth = imp.getBitDepth();
      }
    }

    File newXMLfile = new File(directory + basename + ".vvd");
    writeXML(newXMLfile, doc);

    for (int l = 1; l < lv; l++) {
      imp = WindowManager.getImage(lvImgTitle.get(l));
      imp.changes = false;
      imp.close();
    }
  }
Beispiel #30
0
  private void geterrors() {
    GenericDialog gd = new GenericDialog("Options");
    float conf = 0.67f;
    gd.addNumericField("Confidence Limit", (int) (conf * 100.0f), 5, 10, null);
    gd.addChoice("Error Parameter", paramsnames, paramsnames[0]);
    double spacing = 0.01;
    gd.addNumericField("Chi^2 plot spacing (% of value)?", spacing * 100.0, 2, 10, null);
    boolean globalerror = false;
    gd.addCheckbox("Global Fit Error?", globalerror);
    int dataset = 0;
    gd.addNumericField("Data Set (for Global Error)", dataset, 0);
    gd.showDialog();
    if (gd.wasCanceled()) {
      return;
    }
    conf = 0.01f * (float) gd.getNextNumber();
    int paramindex = (int) gd.getNextChoiceIndex();
    spacing = 0.01 * gd.getNextNumber();
    globalerror = gd.getNextBoolean();
    dataset = (int) gd.getNextNumber();

    if (globalerror) {
      support_plane_errors erclass = new support_plane_errors(this, 0.0001, 50, true, 0.1);
      int[] erindeces = {paramindex, dataset};
      // need to set up all the matrices
      int nsel = 0;
      int nparams = 11;
      for (int i = 0; i < ncurves; i++) {
        if (include[i]) {
          nsel++;
        }
      }
      double[][] params = new double[nsel][nparams];
      String[][] tempformulas = new String[nsel][nparams];
      double[][][] constraints = new double[2][nsel][nparams];
      int[][] vflmatrix = new int[nsel][nparams];

      float[][] tempdata = new float[nsel][xpts * ypts];
      float[][] tempweights = new float[nsel][xpts * ypts];

      int nfit = 0;
      int counter = 0;
      for (int i = 0; i < ncurves; i++) {
        if (include[i]) {
          for (int j = 0; j < nparams; j++) {
            params[counter][j] = globalparams[i][j];
            tempformulas[counter][j] = globalformulas[i][j];
            constraints[0][counter][j] = globalconstraints[0][i][j];
            constraints[1][counter][j] = globalconstraints[1][i][j];
            vflmatrix[counter][j] = globalvflmatrix[i][j];
            if (vflmatrix[counter][j] == 0 || (j == 0 && vflmatrix[counter][j] == 2)) {
              nfit++;
            }
          }
          for (int j = 0; j < xpts; j++) {
            for (int k = 0; k < ypts; k++) {
              tempdata[counter][j + k * xpts] = (float) ((double) pch[i][j][k] / (double) nmeas[i]);
              tempweights[counter][j + k * xpts] = weights[i][j][k];
            }
          }
          counter++;
        }
      }
      int dofnum = xpts * ypts * nsel - (nfit - 1) - 1;
      int dofden = xpts * ypts * nsel - nfit - 1;
      // double flim=FLimit(dofnum,dofden,(double)conf);
      double flim = (new jdist()).FLimit(dofnum, dofden, (double) conf);
      IJ.log("FLimit = " + (float) flim);
      if (flim == Double.NaN && flim < 1.0) {
        IJ.showMessage("Invalid Limiting F Value");
        return;
      }
      double truespacing = Math.abs(params[erindeces[1]][erindeces[0]] * spacing);
      double[][] c2plot =
          erclass.geterrorsglobal(
              params,
              vflmatrix,
              tempformulas,
              paramsnames,
              constraints,
              tempdata,
              tempweights,
              flim,
              truespacing,
              erindeces);
      IJ.log("upper limit = " + c2plot[1][0] + " lower limit = " + c2plot[0][0]);
      int templength = c2plot[0].length;
      float[][] c2plotf = new float[2][templength - 1];
      for (int i = 0; i < (templength - 1); i++) {
        c2plotf[0][i] = (float) c2plot[0][i + 1];
        c2plotf[1][i] = (float) c2plot[1][i + 1];
      }
      new PlotWindow4(
              "c2 plot",
              paramsnames[paramindex] + "[" + dataset + "]",
              "Chi^2",
              c2plotf[0],
              c2plotf[1])
          .draw();
    } else {
      support_plane_errors erclass = new support_plane_errors(this, 0.0001, 50, false, 0.1);
      int errindex = paramindex;

      float[] tempdata = new float[xpts * ypts];
      float[] tempweights = new float[xpts * ypts];
      for (int i = 0; i < xpts; i++) {
        for (int j = 0; j < ypts; j++) {
          tempdata[i + j * xpts] = (float) ((double) avg[i][j] / (double) nmeas[ncurves]);
          tempweights[i + j * xpts] = avgweights[i][j];
        }
      }

      int nfit = 0;
      for (int i = 0; i < 7; i++) {
        if (avgfixes[i] == 0) {
          nfit++;
        }
      }
      int dofnum = xpts * ypts - (nfit - 1) - 1;
      int dofden = xpts * ypts - nfit - 1;
      double flim = (new jdist()).FLimit(dofnum, dofden, (double) conf);
      IJ.log("FLimit = " + (float) flim);
      if (flim == Double.NaN && flim < 1.0) {
        IJ.showMessage("Invalid Limiting F Value");
        return;
      }
      double truespacing = Math.abs(avgparams[errindex] * spacing);
      double[][] c2plot =
          erclass.geterrors(
              avgparams,
              avgfixes,
              avgconstraints,
              tempdata,
              tempweights,
              flim,
              truespacing,
              errindex);
      IJ.log("upper limit = " + c2plot[1][0] + " lower limit = " + c2plot[0][0]);
      int templength = c2plot[0].length;
      float[][] c2plotf = new float[2][templength - 1];
      for (int i = 0; i < (templength - 1); i++) {
        c2plotf[0][i] = (float) c2plot[0][i + 1];
        c2plotf[1][i] = (float) c2plot[1][i + 1];
      }
      new PlotWindow4("c2 plot", paramsnames[errindex], "Chi^2", c2plotf[0], c2plotf[1]).draw();
    }
  }