Beispiel #1
0
  public void run(String arg) {
    ImagePlus imp = WindowManager.getCurrentImage();
    if (imp == null) {
      IJ.noImage();
      return;
    }

    ImageStack stack1 = imp.getStack();
    String fileName = imp.getTitle();
    int endslice = stack1.getSize();

    ImagePlus imp2 = duplicateStack(imp);
    imp2.show();
    String duplicateName = imp2.getTitle();
    // IJ.showMessage("Box",fileName);
    ImageStack stack2 = imp2.getStack();
    stack1.deleteSlice(1);
    stack2.deleteSlice(endslice);

    String calculatorstring =
        ("image1='"
            + fileName
            + "' operation=Subtract image2="
            + imp2.getTitle()
            + " create stack");

    IJ.run("Image Calculator...", calculatorstring);
    ImagePlus imp3 = WindowManager.getCurrentImage();
    imp3.setTitle(fileName + " DeltaF up");
    imp2.getWindow().close();
    imp.getWindow().close();
  }
Beispiel #2
0
 private String getExifData(ImagePlus imp) {
   FileInfo fi = imp.getOriginalFileInfo();
   if (fi == null) return null;
   String directory = fi.directory;
   String name = fi.fileName;
   if (directory == null) return null;
   if ((name == null || name.equals("")) && imp.getStack().isVirtual())
     name = imp.getStack().getSliceLabel(imp.getCurrentSlice());
   if (name == null || !(name.endsWith("jpg") || name.endsWith("JPG"))) return null;
   String path = directory + name;
   String metadata = null;
   try {
     Class c = IJ.getClassLoader().loadClass("Exif_Reader");
     if (c == null) return null;
     String methodName = "getMetadata";
     Class[] argClasses = new Class[1];
     argClasses[0] = methodName.getClass();
     Method m = c.getMethod("getMetadata", argClasses);
     Object[] args = new Object[1];
     args[0] = path;
     Object obj = m.invoke(null, args);
     metadata = obj != null ? obj.toString() : null;
   } catch (Exception e) {
     return null;
   }
   if (metadata != null && !metadata.startsWith("Error:")) return metadata;
   else return null;
 }
Beispiel #3
0
 void scale(ImageProcessor ip) {
   if (newWindow) {
     Rectangle r = ip.getRoi();
     ImagePlus imp2 = imp.createImagePlus();
     imp2.setProcessor(title, ip.resize(newWidth, newHeight));
     Calibration cal = imp2.getCalibration();
     if (cal.scaled()) {
       cal.pixelWidth *= 1.0 / xscale;
       cal.pixelHeight *= 1.0 / yscale;
     }
     imp2.show();
     imp.trimProcessor();
     imp2.trimProcessor();
     imp2.changes = true;
   } else {
     if (processStack && imp.getStackSize() > 1) {
       Undo.reset();
       StackProcessor sp = new StackProcessor(imp.getStack(), ip);
       sp.scale(xscale, yscale, bgValue);
     } else {
       ip.snapshot();
       Undo.setup(Undo.FILTER, imp);
       ip.setSnapshotCopyMode(true);
       ip.scale(xscale, yscale);
       ip.setSnapshotCopyMode(false);
     }
     imp.killRoi();
     imp.updateAndDraw();
     imp.changes = true;
   }
 }
Beispiel #4
0
 public void reduceHyperstack(ImagePlus imp, int factor, boolean reduceSlices) {
   int channels = imp.getNChannels();
   int slices = imp.getNSlices();
   int frames = imp.getNFrames();
   int zfactor = reduceSlices ? factor : 1;
   int tfactor = reduceSlices ? 1 : factor;
   ImageStack stack = imp.getStack();
   ImageStack stack2 = new ImageStack(imp.getWidth(), imp.getHeight());
   boolean virtual = stack.isVirtual();
   int slices2 = slices / zfactor + ((slices % zfactor) != 0 ? 1 : 0);
   int frames2 = frames / tfactor + ((frames % tfactor) != 0 ? 1 : 0);
   int n = channels * slices2 * frames2;
   int count = 1;
   for (int t = 1; t <= frames; t += tfactor) {
     for (int z = 1; z <= slices; z += zfactor) {
       for (int c = 1; c <= channels; c++) {
         int i = imp.getStackIndex(c, z, t);
         IJ.showProgress(i, n);
         ImageProcessor ip = stack.getProcessor(imp.getStackIndex(c, z, t));
         // IJ.log(count++ +"  "+i+" "+c+" "+z+" "+t);
         stack2.addSlice(stack.getSliceLabel(i), ip);
       }
     }
   }
   imp.setStack(stack2, channels, slices2, frames2);
   Calibration cal = imp.getCalibration();
   if (cal.scaled()) cal.pixelDepth *= zfactor;
   if (virtual) imp.setTitle(imp.getTitle());
   IJ.showProgress(1.0);
 }
Beispiel #5
0
 public void run(ImageProcessor ip) {
   if (enlarge && gd.wasOKed())
     synchronized (this) {
       if (!isEnlarged) {
         enlargeCanvas();
         isEnlarged = true;
       }
     }
   if (isEnlarged) { // enlarging may have made the ImageProcessor invalid, also for the parallel
                     // threads
     int slice = pfr.getSliceNumber();
     if (imp.getStackSize() == 1) ip = imp.getProcessor();
     else ip = imp.getStack().getProcessor(slice);
   }
   ip.setInterpolationMethod(interpolationMethod);
   if (fillWithBackground) {
     Color bgc = Toolbar.getBackgroundColor();
     if (bitDepth == 8) ip.setBackgroundValue(ip.getBestIndex(bgc));
     else if (bitDepth == 24) ip.setBackgroundValue(bgc.getRGB());
   } else ip.setBackgroundValue(0);
   ip.rotate(angle);
   if (!gd.wasOKed()) drawGridLines(gridLines);
   if (isEnlarged && imp.getStackSize() == 1) {
     imp.changes = true;
     imp.updateAndDraw();
     Undo.setup(Undo.COMPOUND_FILTER_DONE, imp);
   }
 }
 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);
 }
 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;
 }
 public void splitRGB(ImagePlus imp) {
   boolean keepSource = IJ.altKeyDown();
   String title = imp.getTitle();
   Calibration cal = imp.getCalibration();
   int pos = imp.getCurrentSlice();
   ImageStack[] channels = splitRGB(imp.getStack(), keepSource);
   if (!keepSource) {
     imp.unlock();
     imp.changes = false;
     imp.close();
   }
   ImagePlus rImp = new ImagePlus(title + " (red)", channels[0]);
   rImp.setCalibration(cal);
   rImp.show();
   rImp.setSlice(pos);
   if (IJ.isMacOSX()) IJ.wait(500);
   ImagePlus gImp = new ImagePlus(title + " (green)", channels[1]);
   gImp.setCalibration(cal);
   gImp.show();
   gImp.setSlice(pos);
   if (IJ.isMacOSX()) IJ.wait(500);
   ImagePlus bImp = new ImagePlus(title + " (blue)", channels[2]);
   bImp.setCalibration(cal);
   bImp.show();
   bImp.setSlice(pos);
 }
Beispiel #9
0
 private void doHSRGBProjection(ImagePlus rgbImp) {
   ImageStack stack = rgbImp.getStack();
   ImageStack stack2 = new ImageStack(stack.getWidth(), stack.getHeight());
   for (int i = startSlice; i <= stopSlice; i++) stack2.addSlice(null, stack.getProcessor(i));
   startSlice = 1;
   stopSlice = stack2.getSize();
   doRGBProjection(stack2);
 }
Beispiel #10
0
 private void doRGBProjection(ImageStack stack) {
   ImageStack[] channels = ChannelSplitter.splitRGB(stack, true);
   ImagePlus red = new ImagePlus("Red", channels[0]);
   ImagePlus green = new ImagePlus("Green", channels[1]);
   ImagePlus blue = new ImagePlus("Blue", channels[2]);
   imp.unlock();
   ImagePlus saveImp = imp;
   imp = red;
   color = "(red)";
   doProjection();
   ImagePlus red2 = projImage;
   imp = green;
   color = "(green)";
   doProjection();
   ImagePlus green2 = projImage;
   imp = blue;
   color = "(blue)";
   doProjection();
   ImagePlus blue2 = projImage;
   int w = red2.getWidth(), h = red2.getHeight(), d = red2.getStackSize();
   if (method == SD_METHOD) {
     ImageProcessor r = red2.getProcessor();
     ImageProcessor g = green2.getProcessor();
     ImageProcessor b = blue2.getProcessor();
     double max = 0;
     double rmax = r.getStatistics().max;
     if (rmax > max) max = rmax;
     double gmax = g.getStatistics().max;
     if (gmax > max) max = gmax;
     double bmax = b.getStatistics().max;
     if (bmax > max) max = bmax;
     double scale = 255 / max;
     r.multiply(scale);
     g.multiply(scale);
     b.multiply(scale);
     red2.setProcessor(r.convertToByte(false));
     green2.setProcessor(g.convertToByte(false));
     blue2.setProcessor(b.convertToByte(false));
   }
   RGBStackMerge merge = new RGBStackMerge();
   ImageStack stack2 =
       merge.mergeStacks(w, h, d, red2.getStack(), green2.getStack(), blue2.getStack(), true);
   imp = saveImp;
   projImage = new ImagePlus(makeTitle(), stack2);
 }
 public static ImageStack getChannel(ImagePlus imp, int c) {
   ImageStack stack1 = imp.getStack();
   ImageStack stack2 = new ImageStack(imp.getWidth(), imp.getHeight());
   for (int t = 1; t <= imp.getNFrames(); t++) {
     for (int z = 1; z <= imp.getNSlices(); z++) {
       int n = imp.getStackIndex(c, z, t);
       stack2.addSlice(stack1.getProcessor(n));
     }
   }
   return stack2;
 }
Beispiel #12
0
  /** Performs actual projection using specified method. */
  public void doProjection() {
    if (imp == null) return;
    sliceCount = 0;
    if (method < AVG_METHOD || method > MEDIAN_METHOD) method = AVG_METHOD;
    for (int slice = startSlice; slice <= stopSlice; slice += increment) sliceCount++;
    if (method == MEDIAN_METHOD) {
      projImage = doMedianProjection();
      return;
    }

    // Create new float processor for projected pixels.
    FloatProcessor fp = new FloatProcessor(imp.getWidth(), imp.getHeight());
    ImageStack stack = imp.getStack();
    RayFunction rayFunc = getRayFunction(method, fp);
    if (IJ.debugMode == true) {
      IJ.log("\nProjecting stack from: " + startSlice + " to: " + stopSlice);
    }

    // Determine type of input image. Explicit determination of
    // processor type is required for subsequent pixel
    // manipulation.  This approach is more efficient than the
    // more general use of ImageProcessor's getPixelValue and
    // putPixel methods.
    int ptype;
    if (stack.getProcessor(1) instanceof ByteProcessor) ptype = BYTE_TYPE;
    else if (stack.getProcessor(1) instanceof ShortProcessor) ptype = SHORT_TYPE;
    else if (stack.getProcessor(1) instanceof FloatProcessor) ptype = FLOAT_TYPE;
    else {
      IJ.error("Z Project", "Non-RGB stack required");
      return;
    }

    // Do the projection.
    for (int n = startSlice; n <= stopSlice; n += increment) {
      IJ.showStatus("ZProjection " + color + ": " + n + "/" + stopSlice);
      IJ.showProgress(n - startSlice, stopSlice - startSlice);
      projectSlice(stack.getPixels(n), rayFunc, ptype);
    }

    // Finish up projection.
    if (method == SUM_METHOD) {
      fp.resetMinAndMax();
      projImage = new ImagePlus(makeTitle(), fp);
    } else if (method == SD_METHOD) {
      rayFunc.postProcess();
      fp.resetMinAndMax();
      projImage = new ImagePlus(makeTitle(), fp);
    } else {
      rayFunc.postProcess();
      projImage = makeOutputImage(imp, fp, ptype);
    }

    if (projImage == null) IJ.error("Z Project", "Error computing projection.");
  }
Beispiel #13
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 #14
0
 void setStackDisplayRange(ImagePlus imp) {
   ImageStack stack = imp.getStack();
   double min = Double.MAX_VALUE;
   double max = -Double.MAX_VALUE;
   int n = stack.getSize();
   for (int i = 1; i <= n; i++) {
     if (!silentMode) IJ.showStatus("Calculating stack min and max: " + i + "/" + n);
     ImageProcessor ip = stack.getProcessor(i);
     ip.resetMinAndMax();
     if (ip.getMin() < min) min = ip.getMin();
     if (ip.getMax() > max) max = ip.getMax();
   }
   imp.getProcessor().setMinAndMax(min, max);
   imp.updateAndDraw();
 }
Beispiel #15
0
 public String getImageInfo(ImagePlus imp, ImageProcessor ip) {
   String infoProperty = null;
   if (imp.getStackSize() > 1) {
     ImageStack stack = imp.getStack();
     String label = stack.getSliceLabel(imp.getCurrentSlice());
     if (label != null && label.indexOf('\n') > 0) infoProperty = label;
   }
   if (infoProperty == null) {
     infoProperty = (String) imp.getProperty("Info");
     if (infoProperty == null) infoProperty = getExifData(imp);
   }
   String info = getInfo(imp, ip);
   if (infoProperty != null) return infoProperty + "\n------------------------\n" + info;
   else return info;
 }
Beispiel #16
0
 // at the very end - show output image (if the is a separate one)
 private void showOutput() {
   if (interrupted) return;
   if (outStack != null) {
     outImp = new ImagePlus(TITLE_PREFIX[processType] + imp.getShortTitle(), outStack);
     int[] d = imp.getDimensions();
     outImp.setDimensions(d[2], d[3], d[4]);
     for (int i = 1; i <= imp.getStackSize(); i++)
       outStack.setSliceLabel(imp.getStack().getSliceLabel(i), i);
   }
   if (outImageType != BYTE_OVERWRITE) {
     ImageProcessor ip = outImp.getProcessor();
     if (!Prefs.blackBackground) ip.invertLut();
     ip.resetMinAndMax();
     outImp.show();
   }
 }
Beispiel #17
0
 public void run(String arg) {
   imp = WindowManager.getCurrentImage();
   if (imp == null) {
     IJ.noImage();
     return;
   }
   ImageStack stack = imp.getStack();
   int size = stack.getSize();
   if (size == 1 || (imp.getNChannels() == size && imp.isComposite())) {
     IJ.error("Stack or hyperstack required");
     return;
   }
   if (!showDialog(stack)) return;
   if (hyperstack) reduceHyperstack(imp, factor, reduceSlices);
   else reduceStack(imp, factor);
 }
Beispiel #18
0
 public void reduceStack(ImagePlus imp, int factor) {
   ImageStack stack = imp.getStack();
   boolean virtual = stack.isVirtual();
   int n = stack.getSize();
   ImageStack stack2 = new ImageStack(stack.getWidth(), stack.getHeight());
   for (int i = 1; i <= n; i += factor) {
     if (virtual) IJ.showProgress(i, n);
     stack2.addSlice(stack.getSliceLabel(i), stack.getProcessor(i));
   }
   imp.setStack(null, stack2);
   if (virtual) {
     IJ.showProgress(1.0);
     imp.setTitle(imp.getTitle());
   }
   Calibration cal = imp.getCalibration();
   if (cal.scaled()) cal.pixelDepth *= factor;
 }
Beispiel #19
0
 void createNewStack(ImagePlus imp, ImageProcessor ip) {
   int nSlices = imp.getStackSize();
   int w = imp.getWidth(), h = imp.getHeight();
   ImagePlus imp2 = imp.createImagePlus();
   Rectangle r = ip.getRoi();
   boolean crop = r.width != imp.getWidth() || r.height != imp.getHeight();
   ImageStack stack1 = imp.getStack();
   ImageStack stack2 = new ImageStack(newWidth, newHeight);
   ImageProcessor ip1, ip2;
   int method = interpolationMethod;
   if (w == 1 || h == 1) method = ImageProcessor.NONE;
   for (int i = 1; i <= nSlices; i++) {
     IJ.showStatus("Scale: " + i + "/" + nSlices);
     ip1 = stack1.getProcessor(i);
     String label = stack1.getSliceLabel(i);
     if (crop) {
       ip1.setRoi(r);
       ip1 = ip1.crop();
     }
     ip1.setInterpolationMethod(method);
     ip2 = ip1.resize(newWidth, newHeight, averageWhenDownsizing);
     if (ip2 != null) stack2.addSlice(label, ip2);
     IJ.showProgress(i, nSlices);
   }
   imp2.setStack(title, stack2);
   Calibration cal = imp2.getCalibration();
   if (cal.scaled()) {
     cal.pixelWidth *= 1.0 / xscale;
     cal.pixelHeight *= 1.0 / yscale;
   }
   IJ.showProgress(1.0);
   int[] dim = imp.getDimensions();
   imp2.setDimensions(dim[2], dim[3], dim[4]);
   if (imp.isComposite()) {
     imp2 = new CompositeImage(imp2, ((CompositeImage) imp).getMode());
     ((CompositeImage) imp2).copyLuts(imp);
   }
   if (imp.isHyperStack()) imp2.setOpenAsHyperStack(true);
   if (newDepth > 0 && newDepth != oldDepth)
     imp2 = (new Resizer()).zScale(imp2, newDepth, interpolationMethod);
   if (imp2 != null) {
     imp2.show();
     imp2.changes = true;
   }
 }
Beispiel #20
0
 ImagePlus duplicateStack(ImagePlus img1) {
   ImageStack stack1 = img1.getStack();
   int width = stack1.getWidth();
   int height = stack1.getHeight();
   int n = stack1.getSize();
   ImageStack stack2 = img1.createEmptyStack();
   try {
     for (int i = 1; i <= n; i++) {
       ImageProcessor ip1 = stack1.getProcessor(i);
       ip1.resetRoi();
       ImageProcessor ip2 = ip1.crop();
       stack2.addSlice(stack1.getSliceLabel(i), ip2);
     }
   } catch (OutOfMemoryError e) {
     stack2.trim();
     stack2 = null;
     return null;
   }
   return new ImagePlus("Duplicate", stack2);
 }
Beispiel #21
0
 void createNewStack(ImagePlus imp, ImageProcessor ip) {
   Rectangle r = ip.getRoi();
   boolean crop = r.width != imp.getWidth() || r.height != imp.getHeight();
   int nSlices = imp.getStackSize();
   ImageStack stack1 = imp.getStack();
   ImageStack stack2 = new ImageStack(newWidth, newHeight);
   ImageProcessor ip1, ip2;
   boolean interp = interpolate;
   if (imp.getWidth() == 1 || imp.getHeight() == 1) interp = false;
   for (int i = 1; i <= nSlices; i++) {
     IJ.showStatus("Scale: " + i + "/" + nSlices);
     ip1 = stack1.getProcessor(i);
     String label = stack1.getSliceLabel(i);
     if (crop) {
       ip1.setRoi(r);
       ip1 = ip1.crop();
     }
     ip1.setInterpolate(interp);
     ip2 = ip1.resize(newWidth, newHeight);
     if (ip2 != null) stack2.addSlice(label, ip2);
     IJ.showProgress(i, nSlices);
   }
   ImagePlus imp2 = imp.createImagePlus();
   imp2.setStack(title, stack2);
   Calibration cal = imp2.getCalibration();
   if (cal.scaled()) {
     cal.pixelWidth *= 1.0 / xscale;
     cal.pixelHeight *= 1.0 / yscale;
   }
   int[] dim = imp.getDimensions();
   imp2.setDimensions(dim[2], dim[3], dim[4]);
   IJ.showProgress(1.0);
   if (imp.isComposite()) {
     imp2 = new CompositeImage(imp2, 0);
     ((CompositeImage) imp2).copyLuts(imp);
   }
   if (imp.isHyperStack()) imp2.setOpenAsHyperStack(true);
   imp2.show();
   imp2.changes = true;
 }
Beispiel #22
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);
 }
 /** Splits the specified image into separate channels. */
 public static ImagePlus[] split(ImagePlus imp) {
   if (imp.getType() == ImagePlus.COLOR_RGB) {
     ImageStack[] stacks = splitRGB(imp.getStack(), true);
     ImagePlus[] images = new ImagePlus[3];
     images[0] = new ImagePlus("red", stacks[0]);
     images[1] = new ImagePlus("green", stacks[1]);
     images[2] = new ImagePlus("blue", stacks[2]);
     return images;
   }
   int width = imp.getWidth();
   int height = imp.getHeight();
   int channels = imp.getNChannels();
   int slices = imp.getNSlices();
   int frames = imp.getNFrames();
   int bitDepth = imp.getBitDepth();
   int size = slices * frames;
   Vector images = new Vector();
   HyperStackReducer reducer = new HyperStackReducer(imp);
   for (int c = 1; c <= channels; c++) {
     ImageStack stack2 = new ImageStack(width, height, size); // create empty stack
     stack2.setPixels(
         imp.getProcessor().getPixels(), 1); // can't create ImagePlus will null 1st image
     ImagePlus imp2 = new ImagePlus("C" + c + "-" + imp.getTitle(), stack2);
     stack2.setPixels(null, 1);
     imp.setPosition(c, 1, 1);
     imp2.setDimensions(1, slices, frames);
     imp2.setCalibration(imp.getCalibration());
     reducer.reduce(imp2);
     if (imp.isComposite() && ((CompositeImage) imp).getMode() == IJ.GRAYSCALE)
       IJ.run(imp2, "Grays", "");
     if (imp2.getNDimensions() > 3) imp2.setOpenAsHyperStack(true);
     images.add(imp2);
   }
   ImagePlus[] array = new ImagePlus[images.size()];
   return (ImagePlus[]) images.toArray(array);
 }
Beispiel #24
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;
  }
 public void run(String arg) {
   String[] labels = {
     "Masked_Chromosomes", "Unmixed_Image", "Spectral_Image(optional)", "Spectra(optional)"
   };
   ImagePlus[] imps = jutils.selectImages(true, 4, labels);
   if (imps == null) {
     return;
   }
   if (imps[0] == null) {
     return;
   }
   float[] mask = (float[]) imps[0].getStack().getPixels(2);
   findblobs3 fb = new findblobs3(imps[0].getWidth(), imps[0].getHeight());
   float[] objects = fb.dofindblobs(mask, 0.5f);
   WaitForUserDialog dg =
       new WaitForUserDialog(
           "Optional Input", "Place RoiManager Points on Chromosome Segments (if desired)");
   dg.show();
   if (!dg.escPressed()) {
     RoiManager rman = RoiManager.getInstance();
     while (rman != null && rman.getCount() > 1) {
       Roi[] rois = rman.getRoisAsArray();
       int[] ids = new int[rois.length];
       for (int i = 0; i < rois.length; i++) {
         Rectangle r = rois[i].getBounds();
         ids[i] = (int) objects[r.x + fb.width * r.y];
       }
       objects = fb.link_objects(objects, ids);
       rman.reset();
       dg =
           new WaitForUserDialog(
               "Optional Input",
               "Place More RoiManager Points on Chromosome Segments (if desired)");
       dg.show();
       if (dg.escPressed()) break;
     }
   }
   int[] areas = fb.get_areas(objects);
   int[] temprank = jsort.get_javasort_order(areas);
   int[] arearank = jsort.get_javasort_order(temprank);
   for (int i = 0; i < fb.nobjects; i++) {
     arearank[i] = fb.nobjects - arearank[i] - 1;
   }
   // if the spectra are available, get them
   float[][][] spectra = null;
   Object[] data = null;
   if (imps[1] != null && imps[2] != null && imps[3] != null) {
     ImageWindow iw = imps[3].getWindow();
     if (iw.getClass().getName().equals("jguis.PlotWindow4")) {
       float[][] yvals = (float[][]) jutils.runPW4VoidMethod(iw, "getYValues");
       data = jutils.stack2array(imps[2].getStack());
       Object[] coef = jutils.stack2array(imps[1].getStack());
       spectra = new float[fb.nobjects][2][];
       for (int i = 0; i < fb.nobjects; i++) {
         spectra[i][0] = fb.get_object_spectrum(objects, (i + 1), data, "Sum");
         spectra[i][1] = new float[yvals[0].length];
         float[] tempcoef = fb.get_object_spectrum(objects, (i + 1), coef, "Sum");
         for (int j = 0; j < yvals[0].length; j++) {
           for (int k = 0; k < 5; k++) {
             spectra[i][1][j] += tempcoef[k] * yvals[k][j];
           }
         }
       }
     }
   }
   CompositeImage imp = (CompositeImage) imps[0];
   imp.setPosition(1, 1, 1);
   LUT graylut = jutils.get_lut_for_color(Color.white);
   imp.setChannelColorModel(graylut);
   imp.setPosition(2, 1, 1);
   LUT redlut = jutils.get_lut_for_color(Color.red);
   imp.setChannelColorModel(redlut);
   imp.setPosition(1, 1, 1);
   imp.updateAndRepaintWindow();
   SkyPanel_v3 sp = new SkyPanel_v3();
   int skychan = 6;
   if (imps[1] != null) skychan = imps[1].getNChannels();
   // assume that the sky image has 6 channels and that the second is the unknown green
   // shift the unknown green to the end
   ImagePlus skyimp = null;
   if (imps[1] != null) {
     Object[] skystack = jutils.stack2array(imps[1].getStack());
     // Object[]
     // skystack2={skystack[0],skystack[2],skystack[3],skystack[4],skystack[5],skystack[1]};
     Object[] skystack2 = null;
     if (skychan == 6)
       skystack2 = new Object[] {skystack[0], skystack[2], skystack[3], skystack[4], skystack[5]};
     else
       skystack2 = new Object[] {skystack[0], skystack[1], skystack[2], skystack[3], skystack[4]};
     skyimp =
         new ImagePlus(
             "rearranged", jutils.array2stack(skystack2, imps[1].getWidth(), imps[1].getHeight()));
   }
   int nch = 5;
   if (skyimp != null) nch = skyimp.getStack().getSize();
   GenericDialog gd2 = new GenericDialog("Options");
   gd2.addNumericField("Area Accuracy (percent)", 30, 0);
   for (int i = 0; i < nch; i++) {
     gd2.addNumericField("Ch_" + (i + 1) + "_Contr_Thresh", 0.35, 5, 15, null);
   }
   // gd2.addNumericField("Contribution Threshold",0.35,5,15,null);
   gd2.addCheckbox("Mouse?", false);
   gd2.addNumericField("Box_Width", 150, 0);
   gd2.addNumericField("Box_Height", 100, 0);
   gd2.showDialog();
   if (gd2.wasCanceled()) {
     return;
   }
   sp.areathresh = (float) gd2.getNextNumber();
   sp.objthresh2 = new float[nch];
   for (int i = 0; i < nch; i++) sp.objthresh2[i] = (float) gd2.getNextNumber();
   // sp.objthresh=(float)gd2.getNextNumber();
   boolean mouse = gd2.getNextBoolean();
   int bwidth = (int) gd2.getNextNumber();
   int bheight = (int) gd2.getNextNumber();
   int[] colorindices = {4, 1, 2, 6, 3};
   GenericDialog gd3 = new GenericDialog("Color Options");
   for (int i = 0; i < 5; i++)
     gd3.addChoice(
         "Ch" + (i + 1) + " Color",
         SkyPanel_v3.colornames,
         SkyPanel_v3.colornames[colorindices[i]]);
   gd3.showDialog();
   if (gd3.wasCanceled()) return;
   for (int i = 0; i < 5; i++) colorindices[i] = gd3.getNextChoiceIndex();
   sp.colorindices = colorindices;
   sp.nch = 5;
   sp.dapilast = false;
   sp.cellwidth = bwidth;
   sp.cellheight = bheight;
   sp.init(imps[0], skyimp, objects, areas, arearank, fb, true, spectra, data, mouse);
   SkyPanel_v3.launch_frame(sp);
 }
  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 #27
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");        }      
  public void Calc_5Fr(ImagePlus imp1, ImagePlus imp2) {
    if (imp1.getType() != imp2.getType()) {
      error();
      return;
    }
    if (imp1.getType() == 0) { // getType returns 0 for 8-bit, 1 for 16-bit
      bitDepth = "8-bit";
      Prefs.set("ps.bitDepth", bitDepth);
    } else {
      bitDepth = "16-bit";
      Prefs.set("ps.bitDepth", bitDepth);
    }
    int width = imp1.getWidth();
    int height = imp1.getHeight();
    if (width != imp2.getWidth() || height != imp2.getHeight()) {
      error();
      return;
    }

    ImageStack stack1 = imp1.getStack();
    //		if (bgStackTitle != "NoBg") ImageStack stack2 = imp2.getStack();
    ImageStack stack2 = imp2.getStack();

    ImageProcessor ip = imp1.getProcessor();
    int dimension = width * height;
    byte[] pixB;
    short[] pixS;
    float[][] pixF = new float[5][dimension];
    float[][] pixFBg = new float[5][dimension];

    float a;
    float b;
    float den;
    float aSmp;
    float bSmp;
    float denSmp;
    float aBg;
    float bBg;
    float denBg;
    float retF;
    float azimF;

    byte[] retB = new byte[dimension];
    short[] retS = new short[dimension];
    byte[] azimB = new byte[dimension];
    short[] azimS = new short[dimension];
    // Derived Variables:
    float swingAngle = 2f * (float) Math.PI * swing;
    float tanSwingAngleDiv2 = (float) Math.tan(swingAngle / 2.f);
    float tanSwingAngleDiv2DivSqrt2 = (float) (Math.tan(swingAngle / 2.f) / Math.sqrt(2));
    float wavelengthDiv2Pi = wavelength / (2f * (float) Math.PI);

    // get the pixels of each slice in the stack and convert to float
    for (int i = 0; i < 5; i++) {
      if (bitDepth == "8-bit") {
        pixB = (byte[]) stack1.getPixels(i + 3);
        for (int j = 0; j < dimension; j++) pixF[i][j] = 0xff & pixB[j];
        if (bgStackTitle != "NoBg") {
          pixB = (byte[]) stack2.getPixels(i + 3);
          for (int j = 0; j < dimension; j++) pixFBg[i][j] = 0xff & pixB[j];
        }
      } else {
        pixS = (short[]) stack1.getPixels(i + 3);
        for (int j = 0; j < dimension; j++) pixF[i][j] = (float) pixS[j];
        if (bgStackTitle != "NoBg") {
          pixS = (short[]) stack2.getPixels(i + 3);
          for (int j = 0; j < dimension; j++) pixFBg[i][j] = (float) pixS[j];
        }
      }
    }

    // Algorithm
    // terms a and b
    for (int j = 0; j < dimension; j++) {
      denSmp = (pixF[1][j] + pixF[2][j] + pixF[3][j] + pixF[4][j] - 4 * pixF[0][j]) / 2;
      denBg = denSmp;
      a = (pixF[4][j] - pixF[1][j]);
      aSmp = a;
      aBg = a;
      b = (pixF[2][j] - pixF[3][j]);
      bSmp = b;
      bBg = b;
      if (bgStackTitle != "NoBg") {
        denBg = (pixFBg[1][j] + pixFBg[2][j] + pixFBg[3][j] + pixFBg[4][j] - 4 * pixFBg[0][j]) / 2;
        aBg = pixFBg[4][j] - pixFBg[1][j];
        bBg = pixFBg[2][j] - pixFBg[3][j];
      }
      // Special case of sample retardance half wave, denSmp = 0
      if (denSmp == 0) {
        retF = (float) wavelength / 4;
        azimF =
            (float) (a == 0 & b == 0 ? 0 : (azimRef + 90 + 90 * Math.atan2(a, b) / Math.PI) % 180);
      } else {
        // Retardance, the background correction can be improved by separately considering sample
        // retardance values larger than a quarter wave
        if (bgStackTitle != "NoBg") {
          a = aSmp / denSmp - aBg / denBg;
          b = bSmp / denSmp - bBg / denBg;
        } else {
          a = aSmp / denSmp;
          b = bSmp / denSmp;
        }
        retF = (float) Math.atan(tanSwingAngleDiv2 * Math.sqrt(a * a + b * b));
        if (denSmp < 0) retF = (float) Math.PI - retF;
        retF = retF * wavelengthDiv2Pi; // convert to nm
        if (retF > retCeiling) retF = retCeiling;

        // Orientation
        if ((bgStackTitle == "NoBg") || ((bgStackTitle != "NoBg") && (Math.abs(denSmp) < 1))) {
          a = aSmp;
          b = bSmp;
        }
        azimF =
            (float) (a == 0 & b == 0 ? 0 : (azimRef + 90 + 90 * Math.atan2(a, b) / Math.PI) % 180);
      }
      if (bitDepth == "8-bit") retB[j] = (byte) (((int) (255 * retF / retCeiling)) & 0xff);
      else retS[j] = (short) (4095 * retF / retCeiling);
      if (mirror == "Yes") azimF = 180 - azimF;
      if (bitDepth == "8-bit") azimB[j] = (byte) (((int) azimF) & 0xff);
      else azimS[j] = (short) (azimF * 10f);
    }
    // show the resulting images in slice 1 and 2
    imp1.setSlice(3);
    if (bitDepth == "8-bit") {
      stack1.setPixels(retB, 1);
      stack1.setPixels(azimB, 2);
    } else {
      stack1.setPixels(retS, 1);
      stack1.setPixels(azimS, 2);
    }
    imp1.setSlice(1);
    IJ.selectWindow(imp1.getTitle());

    Prefs.set("ps.sampleStackTitle", sampleStackTitle);
    Prefs.set("ps.bgStackTitle", bgStackTitle);
    Prefs.set("ps.mirror", mirror);
    Prefs.set("ps.wavelength", wavelength);
    Prefs.set("ps.swing", swing);
    Prefs.set("ps.retCeiling", retCeiling);
    Prefs.set("ps.azimRef", azimRef);
    Prefs.savePreferences();
  }
    ImageProcessor setup(ImagePlus imp) {

      ImageProcessor ip;
      int type = imp.getType();
      if (type != ImagePlus.COLOR_RGB) return null;
      ip = imp.getProcessor();
      int id = imp.getID();
      int slice = imp.getCurrentSlice();

      if ((id != previousImageID) | (slice != previousSlice) | (flag)) {
        flag = false; // if true, flags a change from HSB to RGB or viceversa
        numSlices = imp.getStackSize();
        stack = imp.getStack();
        width = stack.getWidth();
        height = stack.getHeight();
        numPixels = width * height;

        hSource = new byte[numPixels];
        sSource = new byte[numPixels];
        bSource = new byte[numPixels];

        // restore = (int[])ip.getPixelsCopy(); //This runs into trouble sometimes, so do it the
        // long way:
        int[] temp = (int[]) ip.getPixels();
        restore = new int[numPixels];
        for (int i = 0; i < numPixels; i++) restore[i] = temp[i];

        fillMask = new int[numPixels];

        // Get hsb or rgb from image.
        ColorProcessor cp = (ColorProcessor) ip;
        IJ.showStatus("Gathering data");

        if (isRGB) cp.getRGB(hSource, sSource, bSource);
        else cp.getHSB(hSource, sSource, bSource);

        IJ.showStatus("done");

        // Create a spectrum ColorModel for the Hue histogram plot.
        Color c;
        byte[] reds = new byte[256];
        byte[] greens = new byte[256];
        byte[] blues = new byte[256];
        for (int i = 0; i < 256; i++) {
          c = Color.getHSBColor(i / 255f, 1f, 1f);

          reds[i] = (byte) c.getRed();
          greens[i] = (byte) c.getGreen();
          blues[i] = (byte) c.getBlue();
        }
        ColorModel cm = new IndexColorModel(8, 256, reds, greens, blues);

        // Make an image with just the hue from the RGB image and the spectrum LUT.
        // This is just for a hue histogram for the plot.  Do not show it.
        // ByteProcessor bpHue = new ByteProcessor(width,height,h,cm);
        ByteProcessor bpHue = new ByteProcessor(width, height, hSource, cm);
        ImagePlus impHue = new ImagePlus("Hue", bpHue);
        // impHue.show();

        ByteProcessor bpSat = new ByteProcessor(width, height, sSource, cm);
        ImagePlus impSat = new ImagePlus("Sat", bpSat);
        // impSat.show();

        ByteProcessor bpBri = new ByteProcessor(width, height, bSource, cm);
        ImagePlus impBri = new ImagePlus("Bri", bpBri);
        // impBri.show();

        plot.setHistogram(impHue, 0);
        splot.setHistogram(impSat, 1);
        bplot.setHistogram(impBri, 2);

        updateLabels();
        updatePlot();
        updateScrollBars();
        imp.updateAndDraw();
      }
      previousImageID = id;
      previousSlice = slice;
      return ip;
    }
  /**
   * 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;
  }