Exemple #1
0
  public static double[] getPixels(ImagePlus imp, int[] slices, int[] frames, int[] channels) {

    ImagePlus subImp = AccessImage.getSubHyperStack(imp, slices, frames, channels);
    ImageStack imageStack = subImp.getImageStack();

    double[] pixels = new double[subImp.getWidth() * subImp.getHeight() * imageStack.getSize()];

    for (int i = 0; i < imageStack.getSize(); i++) {
      switch (subImp.getType()) {
        case ImagePlus.GRAY8:
          ByteProcessor byteProcessor = (ByteProcessor) imageStack.getProcessor(i + 1);
          for (int iX = 0; iX < subImp.getWidth(); iX++) {
            for (int iY = 0; iY < subImp.getHeight(); iY++) {
              pixels[i * subImp.getWidth() * subImp.getHeight() + iY * subImp.getWidth() + iX] =
                  (double) byteProcessor.getPixelValue(iX, iY);
            }
          }
          break;
        case ImagePlus.GRAY16:
          ShortProcessor shortProcessor = (ShortProcessor) imageStack.getProcessor(i + 1);
          for (int iX = 0; iX < subImp.getWidth(); iX++) {
            for (int iY = 0; iY < subImp.getHeight(); iY++) {
              pixels[i * subImp.getWidth() * subImp.getHeight() + iY * subImp.getWidth() + iX] =
                  (double) shortProcessor.getPixelValue(iX, iY);
            }
          }
          break;
        case ImagePlus.GRAY32:
          FloatProcessor floatProcessor = (FloatProcessor) imageStack.getProcessor(i + 1);
          for (int iX = 0; iX < subImp.getWidth(); iX++) {
            for (int iY = 0; iY < subImp.getHeight(); iY++) {
              pixels[i * subImp.getWidth() * subImp.getHeight() + iY * subImp.getWidth() + iX] =
                  (double) floatProcessor.getPixelValue(iX, iY);
            }
          }
          break;
        case ImagePlus.COLOR_RGB:
          ColorProcessor colorProcessor = (ColorProcessor) imageStack.getProcessor(i + 1);
          int nX = subImp.getWidth();
          int nY = subImp.getHeight();
          byte[] red = new byte[nX * nY];
          byte[] green = new byte[nX * nY];
          byte[] blue = new byte[nX * nY];
          colorProcessor.getRGB(red, green, blue);
          int r, g, b;

          for (int j = 0; j < nX * nY; j++) {
            r = red[j] << 16;
            g = green[j] << 8;
            b = blue[j] << 0;
            pixels[i * nX * nY + j] = (double) (r + g + b);
          }
          break;
      }
    }

    return (pixels);
  }
Exemple #2
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();
  }
Exemple #3
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.");
  }
 public void makeTransition(ImagePlus imp, int from, int num) {
   ImageStack stack = imp.getStack();
   int w = imp.getWidth(), h = imp.getHeight();
   ImageProcessor fr = stack.getProcessor(from).duplicate();
   ImageProcessor to = stack.getProcessor(from + 1);
   int[] col = new int[h];
   for (int n = 0; n < num; n++) {
     for (int x = n; x < w; x += num) {
       to.getColumn(x, 0, col, h);
       fr.putColumn(x, 0, col, h);
     }
     stack.addSlice("", fr, from + n);
   }
 }
 public void makeTransition(ImagePlus imp, int from, int num) {
   ImageStack stack = imp.getStack();
   int w = imp.getWidth(), h = imp.getHeight();
   ImageProcessor fr = stack.getProcessor(from).duplicate();
   ImageProcessor to = stack.getProcessor(from + 1);
   int[] row = new int[w];
   for (int n = 0; n < num; n++) {
     for (int y = n; y < h; y += num) {
       to.getRow(0, y, row, w);
       fr.putRow(0, y, row, w);
     }
     stack.addSlice("", fr, from + n);
   }
 }
  private ImagePlus findSurfaceVoxels(final ImagePlus imp) {
    final int w = imp.getWidth();
    final int h = imp.getHeight();
    final int d = imp.getImageStackSize();
    final ImageStack stack = imp.getImageStack();
    final ImageStack surfaceStack = new ImageStack(w, h, d);

    for (int z = 0; z < d; z++) {
      IJ.showStatus("Finding surface voxels");
      final byte[] pixels = (byte[]) stack.getPixels(z + 1);
      surfaceStack.setPixels(pixels.clone(), z + 1);
      final ImageProcessor surfaceIP = surfaceStack.getProcessor(z + 1);
      for (int y = 0; y < h; y++) {
        checkNeighbours:
        for (int x = 0; x < w; x++) {
          if (getPixel(stack, x, y, z, w, h, d) == (byte) 0) continue;
          for (int nz = -1; nz < 2; nz++) {
            final int znz = z + nz;
            for (int ny = -1; ny < 2; ny++) {
              final int yny = y + ny;
              for (int nx = -1; nx < 2; nx++) {
                final int xnx = x + nx;
                final byte pixel = getPixel(stack, xnx, yny, znz, w, h, d);
                if (pixel == (byte) 0) continue checkNeighbours;
              }
            }
          }
          // we checked all the neighbours for a 0
          // but didn't find one, so this is not a surface voxel
          surfaceIP.set(x, y, (byte) 1);
        }
      }
    }
    // turn all the 1's into 0's
    final int wh = w * h;
    for (int z = 0; z < d; z++) {
      IJ.showStatus("Finding surface voxels");
      final ImageProcessor ip = surfaceStack.getProcessor(z + 1);
      for (int i = 0; i < wh; i++) {
        if (ip.get(i) == (byte) 1) ip.set(i, (byte) 0);
      }
    }

    final ImagePlus surfaceImp = new ImagePlus("Surface");
    surfaceImp.setStack(surfaceStack);
    surfaceImp.setCalibration(imp.getCalibration());
    return surfaceImp;
  }
Exemple #7
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);
 }
 /**
  * Splits the specified RGB stack into three 8-bit grayscale stacks. Deletes the source stack if
  * keepSource is false.
  */
 public static ImageStack[] splitRGB(ImageStack rgb, boolean keepSource) {
   int w = rgb.getWidth();
   int h = rgb.getHeight();
   ImageStack[] channels = new ImageStack[3];
   for (int i = 0; i < 3; i++) channels[i] = new ImageStack(w, h);
   byte[] r, g, b;
   ColorProcessor cp;
   int slice = 1;
   int inc = keepSource ? 1 : 0;
   int n = rgb.getSize();
   for (int i = 1; i <= n; i++) {
     IJ.showStatus(i + "/" + n);
     r = new byte[w * h];
     g = new byte[w * h];
     b = new byte[w * h];
     cp = (ColorProcessor) rgb.getProcessor(slice);
     slice += inc;
     cp.getRGB(r, g, b);
     if (!keepSource) rgb.deleteSlice(1);
     channels[0].addSlice(null, r);
     channels[1].addSlice(null, g);
     channels[2].addSlice(null, b);
     IJ.showProgress((double) i / n);
   }
   return channels;
 }
Exemple #9
0
  /**
   * Returns subset of given hyperstack
   *
   * @param imp
   * @param slices
   * @param frames
   * @param channels
   * @return
   */
  public static ImagePlus getSubHyperStack(
      ImagePlus imp, int[] slices, int[] frames, int[] channels) {

    int sizes[] = imp.getDimensions();

    // Zero index --> keep all indices
    if (slices.length == 1 && slices[0] == 0) {
      slices = Commons.getSequence(1, sizes[3]);
    }
    if (frames.length == 1 && frames[0] == 0) {
      frames = Commons.getSequence(1, sizes[4]);
    }
    if (channels.length == 1 && channels[0] == 0) {
      channels = Commons.getSequence(1, sizes[2]);
    }

    // Check input arguments
    if ((Commons.getMin(slices) < 1) || (Commons.getMax(slices) > sizes[3])) {
      System.out.println("Subscripts for slices out of bounds.");
      return imp;
    }
    if ((Commons.getMin(frames) < 1) || (Commons.getMax(frames) > sizes[4])) {
      System.out.println("Subscripts for frames out of bounds.");
      return imp;
    }
    if ((Commons.getMin(channels) < 1) || (Commons.getMax(channels) > sizes[2])) {
      System.out.println("Subscripts for channels out of bounds.");
      return imp;
    }

    // Convert indices into stack indices
    ImageStack ims = imp.getImageStack();
    boolean keep[] = new boolean[ims.getSize()];
    Arrays.fill(keep, false);

    int slicesToKeep = 0;
    for (int i = 0; i < slices.length; i++) {
      for (int j = 0; j < frames.length; j++) {
        for (int k = 0; k < channels.length; k++) {
          int test = imp.getStackIndex(channels[k], slices[i], frames[j]);
          keep[imp.getStackIndex(channels[k], slices[i], frames[j]) - 1] = true;
          slicesToKeep++;
        }
      }
    }

    ImageStack resIms = new ImageStack(imp.getWidth(), imp.getHeight());

    for (int i = 0; i < ims.getSize(); i++) {
      if (keep[i]) {
        resIms.addSlice(ims.getProcessor(i + 1));
      }
    }
    ImagePlus resImp = new ImagePlus("SubHyperStack of " + imp.getTitle(), resIms);
    resImp.setOpenAsHyperStack(true);
    resImp.setDimensions(channels.length, slices.length, frames.length);

    return resImp;
  }
Exemple #10
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);
 }
Exemple #11
0
  /**
   * Calculate the Rand index and its derived statistics in 2D between some original labels and the
   * corresponding proposed labels. Both images are binarized. We follow the definition of Rand
   * index described by William M. Rand \cite{Rand71}.
   *
   * <p>BibTeX:
   *
   * <pre>
   * &#64;article{Rand71,
   *   author    = {William M. Rand},
   *   title     = {Objective criteria for the evaluation of clustering methods},
   *   journal   = {Journal of the American Statistical Association},
   *   year      = {1971},
   *   volume    = {66},
   *   number    = {336},
   *   pages     = {846--850},
   *   doi       = {10.2307/2284239)
   * }
   * </pre>
   *
   * @param binaryThreshold threshold value to binarize proposal (larger than 0 and smaller than 1)
   * @return Rand index value and derived satatistics
   */
  public ClassificationStatistics getRandIndexStats(double binaryThreshold) {
    final ImageStack labelSlices = originalLabels.getImageStack();
    final ImageStack proposalSlices = proposedLabels.getImageStack();

    double randIndex = 0;
    double tp = 0;
    double tn = 0;
    double fp = 0;
    double fn = 0;

    // Executor service to produce concurrent threads
    final ExecutorService exe =
        Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

    final ArrayList<Future<ClassificationStatistics>> futures =
        new ArrayList<Future<ClassificationStatistics>>();

    try {
      for (int i = 1; i <= labelSlices.getSize(); i++) {
        futures.add(
            exe.submit(
                getRandIndexStatsConcurrent(
                    labelSlices.getProcessor(i).convertToFloat(),
                    proposalSlices.getProcessor(i).convertToFloat(),
                    binaryThreshold)));
      }

      // Wait for the jobs to be done
      for (Future<ClassificationStatistics> f : futures) {
        ClassificationStatistics cs = f.get();
        randIndex += cs.metricValue;
        tp += cs.truePositives;
        tn += cs.trueNegatives;
        fp += cs.falsePositives;
        fn += cs.falseNegatives;
      }
    } catch (Exception ex) {
      IJ.log("Error when calculating rand error in a concurrent way.");
      ex.printStackTrace();
    } finally {
      exe.shutdown();
    }

    return new ClassificationStatistics(tp, tn, fp, fn, randIndex / labelSlices.getSize());
  }
Exemple #12
0
  @Override
  public void run(ImageProcessor ip) {
    w = image.getWidth();
    h = image.getHeight();
    float[] rgb = new float[3];
    float[] lab = new float[3];

    if (image.getStack().getSize() == 1) {
      int[] pixels = (int[]) image.getProcessor().getPixels();
      float[] l = new float[w * h];
      float[] a = new float[w * h];
      float[] b = new float[w * h];

      for (int i = 0; i < w * h; i++) {
        int v = pixels[i];
        CIELAB.int2sRGB(v, rgb);
        CIELAB.sRGB2CIELAB(rgb, lab);
        l[i] = lab[0];
        a[i] = lab[1];
        b[i] = lab[2];
      }
      ImageStack stack = new ImageStack(w, h);
      stack.addSlice("L", new FloatProcessor(w, h, l, null));
      stack.addSlice("a", new FloatProcessor(w, h, a, null));
      stack.addSlice("b", new FloatProcessor(w, h, b, null));
      new ImagePlus(image.getTitle() + " Lab", stack).show();
    } else {
      int[] rgbi = new int[3];
      ImageStack stack = image.getStack();
      float[] l = (float[]) stack.getProcessor(1).getPixels();
      float[] a = (float[]) stack.getProcessor(2).getPixels();
      float[] b = (float[]) stack.getProcessor(3).getPixels();
      int[] pixels = new int[w * h];

      for (int i = 0; i < w * h; i++) {
        lab[0] = l[i];
        lab[1] = a[i];
        lab[2] = b[i];
        CIELAB.CIELAB2sRGB(lab, rgb);
        pixels[i] = CIELAB.sRGB2int(rgb);
      }
      ip = new ColorProcessor(w, h, pixels);
      new ImagePlus(image.getTitle() + " RGB", ip).show();
    }
  }
  /** GUI involved test which is run in main function */
  public void testAntiDriftController() {
    final AntiDriftController ct =
        new AntiDriftController(new File("/Users/moon/temp/"), 2, 3, 4, 0, 1, 0);
    ct.startNewStack();

    final ImageStack stackFirst = impFirst.getImageStack();
    for (int k = 1; k <= stackFirst.getSize(); k++) {
      ct.addXYSlice(stackFirst.getProcessor(k));
    }
    ct.finishStack();

    ct.startNewStack();
    final ImageStack stackSecond = impSecond.getImageStack();
    for (int k = 1; k <= stackSecond.getSize(); k++) {
      ct.addXYSlice(stackSecond.getProcessor(k));
    }
    ct.finishStack();
  }
Exemple #14
0
 void setup(int channels, ImageStack stack2) {
   if (stack2 != null
       && stack2.getSize() > 0
       && (stack2.getProcessor(1) instanceof ColorProcessor)) { // RGB?
     cip = null;
     lut = null;
     return;
   }
   setupLuts(channels);
   if (mode == COMPOSITE) {
     cip = new ImageProcessor[channels];
     for (int i = 0; i < channels; ++i) {
       cip[i] = stack2.getProcessor(i + 1);
       cip[i].setLut(lut[i]);
     }
     currentSlice = currentFrame = 1;
   }
 }
  public void run(String arg0) {

    while (numOfIteration <= numberOfImagesToProcess - 1) {

      ImageStack cloudStack = loadImages();

      ref = cloudStack.getProcessor(1); // Referenzbinärbild
      corr = cloudStack.getProcessor(2); // Korrespondenzbinärbild

      // An dieser Stelle kommt das Tracking die entstehenden Listen, kannst du ja mit einer
      // Konsolenausgabe überprüfen

      referenceList = Tracking.startTracking(ref, numOfIteration);
      correspondenceList = Tracking.startTracking(corr, numOfIteration);

      numOfIteration++;
    }
  }
  public ImageStack expandStack(ImageStack stackOld, int wNew, int hNew, int xOff, int yOff) {
    int nFrames = stackOld.getSize();
    ImageProcessor ipOld = stackOld.getProcessor(1);
    java.awt.Color colorBack = Toolbar.getBackgroundColor();

    ImageStack stackNew = new ImageStack(wNew, hNew, stackOld.getColorModel());
    ImageProcessor ipNew;

    for (int i = 1; i <= nFrames; i++) {
      IJ.showProgress((double) i / nFrames);
      ipNew = ipOld.createProcessor(wNew, hNew);
      if (zeroFill) ipNew.setValue(0.0);
      else ipNew.setColor(colorBack);
      ipNew.fill();
      ipNew.insert(stackOld.getProcessor(i), xOff, yOff);
      stackNew.addSlice(stackOld.getSliceLabel(i), ipNew);
    }
    return stackNew;
  }
 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;
 }
 public DataImporter(final String resultsFilePath, final boolean readWeights) {
   super();
   final ImageStack file = IJ.openImage(resultsFilePath).getImageStack();
   slices = file.getSize();
   for (int i = 1; i <= file.getSize(); i++) {
     for (int y = 0; y < file.getHeight(); y++) {
       final float[] point = new float[14];
       for (int x = 0; x < file.getWidth(); x++) {
         point[x] = file.getProcessor(i).getf(x, y);
       }
       this.add(point);
     }
   }
 }
    public void makeTransition(ImagePlus imp, int from, int num) {
      if (from > imp.getStackSize()) {
        IJ.error("Need a following slice to which to transit.");
        return;
      }
      num++; // so that really num slices are added
      ImageStack stack = imp.getStack();
      int[] before = (int[]) (stack.getProcessor(from).convertToRGB().getPixels());
      int[] after = (int[]) (stack.getProcessor(from + 1).convertToRGB().getPixels());

      for (int z = 1; z < num; z++) {
        ColorProcessor bp = new ColorProcessor(stack.getWidth(), stack.getHeight());
        int[] pixels = (int[]) bp.getPixels();
        double dp = z;
        double dn = num - z;

        for (int i = 0; i < pixels.length; i++) {
          pixels[i] = interpolate(before[i], dp, after[i], dn);
        }
        new ImagePlus("slice + " + z, bp).show();
        stack.addSlice("", bp, from + z - 1);
      }
    }
  /** Test anti drift handler. */
  @Test
  public void testAntiDrift() {
    final DefaultAntiDrift proj = new DefaultAntiDrift();
    proj.startNewStack();

    final ImageStack stackFirst = impFirst.getImageStack();
    for (int k = 1; k <= stackFirst.getSize(); k++) {
      proj.addXYSlice(stackFirst.getProcessor(k));
    }
    proj.finishStack();

    proj.startNewStack();
    final ImageStack stackSecond = impSecond.getImageStack();
    for (int k = 1; k <= stackSecond.getSize(); k++) {
      proj.addXYSlice(stackSecond.getProcessor(k));
    }
    proj.finishStack();

    final double DELTA = 1e-5;
    final Vector3D correction = proj.getLastCorrection();
    Assert.assertEquals(16, correction.getX(), DELTA);
    Assert.assertEquals(24, correction.getY(), DELTA);
    Assert.assertEquals(32, correction.getZ(), DELTA);
  }
Exemple #21
0
  /**
   * Calculate the Rand error in 2D between some original labels and the corresponding proposed
   * labels. Both image are binarized. The Rand error is defined as the 1 - Rand index, as described
   * by William M. Rand \cite{Rand71}.
   *
   * <p>BibTeX:
   *
   * <pre>
   * &#64;article{Rand71,
   *   author    = {William M. Rand},
   *   title     = {Objective criteria for the evaluation of clustering methods},
   *   journal   = {Journal of the American Statistical Association},
   *   year      = {1971},
   *   volume    = {66},
   *   number    = {336},
   *   pages     = {846--850},
   *   doi       = {10.2307/2284239)
   * }
   * </pre>
   *
   * @param binaryThreshold threshold value to binarize proposal (larger than 0 and smaller than 1)
   * @return Rand error
   */
  public double getMetricValue(double binaryThreshold) {

    final ImageStack labelSlices = originalLabels.getImageStack();
    final ImageStack proposalSlices = proposedLabels.getImageStack();

    double randError = 0;

    // Executor service to produce concurrent threads
    final ExecutorService exe =
        Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

    final ArrayList<Future<Double>> futures = new ArrayList<Future<Double>>();

    try {
      for (int i = 1; i <= labelSlices.getSize(); i++) {
        futures.add(
            exe.submit(
                getRandErrorConcurrent(
                    labelSlices.getProcessor(i).convertToFloat(),
                    proposalSlices.getProcessor(i).convertToFloat(),
                    binaryThreshold)));
      }

      // Wait for the jobs to be done
      for (Future<Double> f : futures) {
        randError += f.get();
      }
    } catch (Exception ex) {
      IJ.log("Error when calculating rand error in a concurrent way.");
      ex.printStackTrace();
    } finally {
      exe.shutdown();
    }

    return randError / labelSlices.getSize();
  }
Exemple #22
0
 public void resetDisplayRanges() {
   int channels = getNChannels();
   if (lut == null) setupLuts(channels);
   ImageStack stack2 = getImageStack();
   if (lut == null
       || channels != lut.length
       || channels > stack2.getSize()
       || channels > MAX_CHANNELS) return;
   for (int i = 0; i < channels; ++i) {
     ImageProcessor ip2 = stack2.getProcessor(i + 1);
     ip2.resetMinAndMax();
     lut[i].min = ip2.getMin();
     lut[i].max = ip2.getMax();
   }
 }
Exemple #23
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();
 }
Exemple #24
0
  /**
   * Reduce error in thickness quantitation by trimming the one pixel overhang in the thickness map
   *
   * @param imp Binary input image
   * @param impLTC Thickness map
   * @param inv true if calculating thickness of background, false for foreground
   * @return Thickness map with pixels masked by input image
   */
  private ImagePlus trimOverhang(ImagePlus imp, ImagePlus impLTC, boolean inv) {
    final int w = imp.getWidth();
    final int h = imp.getHeight();
    final int d = imp.getImageStackSize();

    final ImageStack stack = imp.getImageStack();
    final ImageStack mapStack = impLTC.getImageStack();

    final int keepValue = inv ? 0 : 255;
    ImageProcessor ip = new ByteProcessor(w, h);
    ImageProcessor map = new FloatProcessor(w, h);
    for (int z = 1; z <= d; z++) {
      IJ.showStatus("Masking thickness map...");
      IJ.showProgress(z, d);
      ip = stack.getProcessor(z);
      map = mapStack.getProcessor(z);
      for (int y = 0; y < h; y++) {
        for (int x = 0; x < w; x++) {
          if (ip.get(x, y) != keepValue) map.set(x, y, 0);
        }
      }
    }
    return impLTC;
  }
Exemple #25
0
  public static ImagePlus multiply(ImagePlus a, double[] b) {

    Duplicator dp = new Duplicator();
    ImagePlus c = dp.run(a);
    IJ.run(c, "32-bit", "");

    ImageStack ims = c.getStack();
    ImagePlus tmpImp;
    for (int i = 0; i < c.getNSlices(); i++) {
      tmpImp = new ImagePlus("tmp", ims.getProcessor(i + 1));
      IJ.run(tmpImp, "Multiply...", "value=" + Double.toString(b[i]));
      ims.setProcessor(tmpImp.getProcessor(), i + 1);
    }

    c = new ImagePlus(a.getTitle() + "_mult", ims);
    return (c);
  }
Exemple #26
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;
 }
Exemple #27
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;
   }
 }
 /**
  * Assigns the data values of a {@link Dataset} from a paired {@link ImagePlus}. Assumes the
  * Dataset and ImagePlus have compatible dimensions and that the data planes are not directly
  * mapped. Gets values via {@link ImageProcessor}::getf(). In cases where there is a narrowing of
  * data into modern ImageJ types the data is range clamped. Does not change the Dataset's
  * metadata.
  */
 @Override
 public void updateDataset(final Dataset ds, final ImagePlus imp) {
   final RealType<?> type = ds.getType();
   final double typeMin = type.getMinValue();
   final double typeMax = type.getMaxValue();
   final boolean signed16BitData = type instanceof ShortType;
   final RandomAccess<? extends RealType<?>> accessor = ds.getImgPlus().randomAccess();
   final long[] dims = ds.getDims();
   final AxisType[] axes = ds.getAxes();
   final int xIndex = ds.getAxisIndex(Axes.X);
   final int yIndex = ds.getAxisIndex(Axes.Y);
   final int zIndex = ds.getAxisIndex(Axes.Z);
   final int tIndex = ds.getAxisIndex(Axes.TIME);
   final int xSize = imp.getWidth();
   final int ySize = imp.getHeight();
   final int zSize = imp.getNSlices();
   final int tSize = imp.getNFrames();
   final int cSize = imp.getNChannels();
   final ImageStack stack = imp.getStack();
   int planeNum = 1;
   final long[] pos = new long[dims.length];
   for (int t = 0; t < tSize; t++) {
     if (tIndex >= 0) pos[tIndex] = t;
     for (int z = 0; z < zSize; z++) {
       if (zIndex >= 0) pos[zIndex] = z;
       for (int c = 0; c < cSize; c++) {
         LegacyUtils.fillChannelIndices(dims, axes, c, pos);
         final ImageProcessor proc = stack.getProcessor(planeNum++);
         for (int x = 0; x < xSize; x++) {
           if (xIndex >= 0) pos[xIndex] = x;
           for (int y = 0; y < ySize; y++) {
             if (yIndex >= 0) pos[yIndex] = y;
             accessor.setPosition(pos);
             double value = proc.getf(x, y);
             if (signed16BitData) value -= 32768.0;
             if (value < typeMin) value = typeMin;
             else if (value > typeMax) value = typeMax;
             accessor.get().setReal(value);
           }
         }
       }
     }
   }
   ds.update();
 }
 // extract range of slices
 ImagePlus stackRange(ImagePlus imp, int first, int last, int inc, String title) throws Exception {
   ImageStack stack = imp.getStack();
   ImageStack stack2 = null;
   Roi roi = imp.getRoi();
   for (int i = first, j = 0; i <= last; i += inc) {
     // IJ.log(first+" "+last+" "+inc+" "+i);
     IJ.showProgress(i - first, last - first);
     int currSlice = i - j;
     ImageProcessor ip2 = stack.getProcessor(currSlice);
     // ip2.setRoi(roi);
     // ip2 = ip2.crop();
     if (stack2 == null) stack2 = new ImageStack(ip2.getWidth(), ip2.getHeight());
     stack2.addSlice(stack.getSliceLabel(currSlice), ip2);
   }
   ImagePlus substack = imp.createImagePlus();
   substack.setStack(title, stack2);
   substack.setCalibration(imp.getCalibration());
   return substack;
 }
Exemple #30
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);
 }