Exemple #1
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 #2
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);
  }
 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);
     }
   }
 }
Exemple #4
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();
  }
  @Test
  public final void testErosionCubicMeshC6() {
    ImageStack mask = createCubicMeshImage();
    invertGray8Stack(mask);

    ImageStack marker = ImageStack.create(20, 20, 20, 8);
    marker.setVoxel(5, 5, 5, 255);
    invertGray8Stack(marker);

    GeodesicReconstruction3DHybrid0Gray8 algo = new GeodesicReconstruction3DHybrid0Gray8();
    algo.setReconstructionType(GeodesicReconstructionType.BY_EROSION);
    algo.setConnectivity(6);

    ImageStack result = algo.applyTo(marker, mask);

    assertEquals(0, result.getVoxel(5, 15, 5), .01);
    assertEquals(255, result.getVoxel(0, 0, 0), .01);

    int sizeX = mask.getWidth();
    int sizeY = mask.getHeight();
    int sizeZ = mask.getSize();

    for (int z = 0; z < sizeZ; z++) {
      for (int y = 0; y < sizeY; y++) {
        for (int x = 0; x < sizeX; x++) {
          assertEquals(result.getVoxel(x, y, z), mask.getVoxel(x, y, z), .01);
        }
      }
    }
  }
  @Test
  public final void testDilationCochleaVolumeC6() {
    String fileName = getClass().getResource("/files/bat-cochlea-volume.tif").getFile();
    ImagePlus imagePlus = IJ.openImage(fileName);

    assertNotNull(imagePlus);

    assertTrue(imagePlus.getStackSize() > 0);

    ImageStack mask = imagePlus.getStack();
    // Ensure regularity of the mask
    mask = Morphology.opening(mask, CubeStrel.fromRadius(1));

    int width = mask.getWidth();
    int height = mask.getHeight();
    int depth = mask.getSize();
    int bitDepth = mask.getBitDepth();
    ImageStack marker = ImageStack.create(width, height, depth, bitDepth);

    marker.setVoxel(20, 80, 50, 255);

    GeodesicReconstruction3DHybrid0Gray8 algo = new GeodesicReconstruction3DHybrid0Gray8();
    algo.setConnectivity(6);
    algo.verbose = false;

    ImageStack result = algo.applyTo(marker, mask);

    for (int z = 0; z < depth; z++) {
      for (int y = 0; y < height; y++) {
        for (int x = 0; x < width; x++) {
          assertEquals(result.getVoxel(x, y, z), mask.getVoxel(x, y, z), .01);
        }
      }
    }
  }
  @Test
  public final void testDilationHilbertCurveC26() {
    String fileName = getClass().getResource("/files/hilbert3d.tif").getFile();
    ImagePlus imagePlus = IJ.openImage(fileName);

    assertNotNull(imagePlus);

    assertTrue(imagePlus.getStackSize() > 0);

    ImageStack mask = imagePlus.getStack();

    int width = mask.getWidth();
    int height = mask.getHeight();
    int depth = mask.getSize();
    int bitDepth = mask.getBitDepth();
    ImageStack marker = ImageStack.create(width, height, depth, bitDepth);

    marker.setVoxel(3, 0, 0, 255);

    GeodesicReconstruction3DHybrid0Gray8 algo = new GeodesicReconstruction3DHybrid0Gray8();
    algo.setConnectivity(26);
    algo.verbose = false;

    ImageStack result = algo.applyTo(marker, mask);

    for (int z = 0; z < depth; z++) {
      for (int y = 0; y < height; y++) {
        for (int x = 0; x < width; x++) {
          assertEquals(result.getVoxel(x, y, z), mask.getVoxel(x, y, z), .01);
        }
      }
    }
  }
  public void run(ImageProcessor ip) {

    dimz = stack.getSize();
    dimy = stack.getWidth();
    dimx = stack.getHeight();

    SaveDialog sd = new SaveDialog("Save Measurements as Text...", "res", ".dat");
    String name = sd.getFileName();
    if (name == null) return;

    String directory = sd.getDirectory();

    nb = calculnb(stack); // -1;
    IJ.showStatus("Measure parameters for the " + nb + " objects ...");
    if (nb < 1) {
      IJ.showMessage("volume must be labeled");
    } else {
      double[] volume_m = new double[nb];
      int[] volume_p = new int[nb];
      double[] surface = new double[nb];
      double[] surfacenb = new double[nb];
      double[][][] I = new double[3][3][nb];
      double[][] J = new double[3][nb];
      double[][][] dir = new double[3][3][nb];
      double[] xg = new double[nb];
      double[] yg = new double[nb];
      double[] zg = new double[nb];
      byte[] bord = new byte[nb];
      //       		double[] a = new double[nb];
      //       		double[] b = new double[nb];
      //       		double[] c = new double[nb];
      //       		double[] Fab = new double[nb];
      //       		double[] Fac = new double[nb];
      //       		double[] Fbc = new double[nb];
      //       		double[] sp = new double[nb];
      double[][] lmin = new double[nb][3];
      double[][] lmax = new double[nb][3];
      IJ.showStatus("Measure surfaces ...");
      calculmarchsurfstack(stack, nb, surface, volume_m);
      calculmarchsurfstacknb(stack, nb, surfacenb);
      // calculvolumestack(stack,nb,volume_p);
      IJ.showStatus("Measure volumes and inertia ...");
      calculcgstack(stack, nb, volume_p, xg, yg, zg);
      calculinertiestack(stack, nb, xg, yg, zg, I);
      inertie(nb, I, J, dir);
      IJ.showStatus("Measure bounding boxes ...");
      boitestack(stack, nb, xg, yg, zg, dir, lmin, lmax);
      borderstack(stack, nb, bord);
      IJ.showStatus("Save results ...");
      sauvegarde(
          volume_p, volume_m, surface, surfacenb, xg, yg, zg, J, dir, nb, bord, lmin, lmax,
          directory, name);
      volume_m = null;
      volume_p = null;
      surface = null;
      xg = null;
      yg = null;
      zg = null;
    }
  }
 /**
  * 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;
 }
  @Test
  public final void testApplyTo() {
    GeodesicReconstructionByDilation3DGray8 algo = new GeodesicReconstructionByDilation3DGray8();

    String fileName = getClass().getResource("/files/bat-cochlea-volume.tif").getFile();
    ImagePlus imagePlus = IJ.openImage(fileName);
    assertNotNull(imagePlus);

    assertTrue(imagePlus.getStackSize() > 0);

    ImageStack mask = imagePlus.getStack();
    int width = mask.getWidth();
    int height = mask.getHeight();
    int depth = mask.getSize();
    int bitDepth = mask.getBitDepth();
    ImageStack marker = ImageStack.create(width, height, depth, bitDepth);

    marker.setVoxel(20, 80, 50, 255);

    ImageStack result = algo.applyTo(marker, mask);

    for (int z = 0; z < depth; z++) {
      for (int y = 0; y < height; y++) {
        for (int x = 0; x < width; x++) {
          assertEquals(result.getVoxel(x, y, z), mask.getVoxel(x, y, z), .01);
        }
      }
    }
  }
  @Test
  public final void testRegionalMaxima_CubicMeshC26() {
    // load the reference image, and get its size
    ImageStack image = createCubicMeshImage();
    int sizeX = image.getWidth();
    int sizeY = image.getHeight();
    int sizeZ = image.getSize();

    // create test image: add a band with value 127 in the middle
    int zMid = sizeZ / 2;
    for (int y = 0; y < sizeY; y++) {
      for (int x = 0; x < sizeX; x++) {
        double val = image.getVoxel(x, y, zMid);
        if (val == 255) image.setVoxel(x, y, zMid, 127);
      }
    }

    ImageStack maxima = MinimaAndMaxima3D.regionalMaxima(image, 26);

    for (int z = 0; z < sizeZ; z++) {
      for (int y = 0; y < sizeY; y++) {
        for (int x = 0; x < sizeX; x++) {
          int v0 = (int) image.getVoxel(x, y, z);
          int v = (int) maxima.getVoxel(x, y, z);
          if (v0 == 255) assertEquals(255, v);
          else assertEquals(0, v);
        }
      }
    }
  }
Exemple #12
0
 /** Opens a stack of images. */
 ImagePlus openStack(ColorModel cm, boolean show) {
   ImageStack stack = new ImageStack(fi.width, fi.height, cm);
   long skip = fi.getOffset();
   Object pixels;
   try {
     ImageReader reader = new ImageReader(fi);
     InputStream is = createInputStream(fi);
     if (is == null) return null;
     IJ.resetEscape();
     for (int i = 1; i <= fi.nImages; i++) {
       if (!silentMode) IJ.showStatus("Reading: " + i + "/" + fi.nImages);
       if (IJ.escapePressed()) {
         IJ.beep();
         IJ.showProgress(1.0);
         silentMode = false;
         return null;
       }
       pixels = reader.readPixels(is, skip);
       if (pixels == null) break;
       stack.addSlice(null, pixels);
       skip = fi.gapBetweenImages;
       if (!silentMode) IJ.showProgress(i, fi.nImages);
     }
     is.close();
   } catch (Exception e) {
     IJ.log("" + e);
   } catch (OutOfMemoryError e) {
     IJ.outOfMemory(fi.fileName);
     stack.trim();
   }
   if (!silentMode) IJ.showProgress(1.0);
   if (stack.getSize() == 0) return null;
   if (fi.sliceLabels != null && fi.sliceLabels.length <= stack.getSize()) {
     for (int i = 0; i < fi.sliceLabels.length; i++) stack.setSliceLabel(fi.sliceLabels[i], i + 1);
   }
   ImagePlus imp = new ImagePlus(fi.fileName, stack);
   if (fi.info != null) imp.setProperty("Info", fi.info);
   if (show) imp.show();
   imp.setFileInfo(fi);
   setCalibration(imp);
   ImageProcessor ip = imp.getProcessor();
   if (ip.getMin() == ip.getMax()) // find stack min and max if first slice is blank
   setStackDisplayRange(imp);
   if (!silentMode) IJ.showProgress(1.0);
   silentMode = false;
   return imp;
 }
Exemple #13
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);
 }
  private final void assertStackEquals(ImageStack image, ImageStack image2) {
    int sizeX = image.getWidth();
    int sizeY = image.getHeight();
    int sizeZ = image.getSize();

    assertEquals(sizeX, image2.getWidth());
    assertEquals(sizeY, image2.getHeight());
    assertEquals(sizeZ, image2.getSize());

    for (int z = 0; z < sizeZ; z++) {
      for (int y = 0; y < sizeY; y++) {
        for (int x = 0; x < sizeX; x++) {
          assertEquals(image.getVoxel(x, y, z), image2.getVoxel(x, y, z), .01);
        }
      }
    }
  }
Exemple #15
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());
  }
  /** 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 #17
0
 void addScrollbars(ImagePlus imp) {
   ImageStack s = imp.getStack();
   int stackSize = s.getSize();
   nSlices = stackSize;
   hyperStack = imp.getOpenAsHyperStack();
   // imp.setOpenAsHyperStack(false);
   int[] dim = imp.getDimensions();
   int nDimensions = 2 + (dim[2] > 1 ? 1 : 0) + (dim[3] > 1 ? 1 : 0) + (dim[4] > 1 ? 1 : 0);
   if (nDimensions <= 3 && dim[2] != nSlices) hyperStack = false;
   if (hyperStack) {
     nChannels = dim[2];
     nSlices = dim[3];
     nFrames = dim[4];
   }
   // IJ.log("StackWindow: "+hyperStack+" "+nChannels+" "+nSlices+" "+nFrames);
   if (nSlices == stackSize) hyperStack = false;
   if (nChannels * nSlices * nFrames != stackSize) hyperStack = false;
   if (cSelector != null || zSelector != null || tSelector != null) removeScrollbars();
   ImageJ ij = IJ.getInstance();
   if (nChannels > 1) {
     cSelector = new ScrollbarWithLabel(this, 1, 1, 1, nChannels + 1, 'c');
     add(cSelector);
     if (ij != null) cSelector.addKeyListener(ij);
     cSelector.addAdjustmentListener(this);
     cSelector.setFocusable(false); // prevents scroll bar from blinking on Windows
     cSelector.setUnitIncrement(1);
     cSelector.setBlockIncrement(1);
   }
   if (nSlices > 1) {
     char label = nChannels > 1 || nFrames > 1 ? 'z' : 't';
     if (stackSize == dim[2] && imp.isComposite()) label = 'c';
     zSelector = new ScrollbarWithLabel(this, 1, 1, 1, nSlices + 1, label);
     if (label == 't') animationSelector = zSelector;
     add(zSelector);
     if (ij != null) zSelector.addKeyListener(ij);
     zSelector.addAdjustmentListener(this);
     zSelector.setFocusable(false);
     int blockIncrement = nSlices / 10;
     if (blockIncrement < 1) blockIncrement = 1;
     zSelector.setUnitIncrement(1);
     zSelector.setBlockIncrement(blockIncrement);
     sliceSelector = zSelector.bar;
   }
   if (nFrames > 1) {
     animationSelector = tSelector = new ScrollbarWithLabel(this, 1, 1, 1, nFrames + 1, 't');
     add(tSelector);
     if (ij != null) tSelector.addKeyListener(ij);
     tSelector.addAdjustmentListener(this);
     tSelector.setFocusable(false);
     int blockIncrement = nFrames / 10;
     if (blockIncrement < 1) blockIncrement = 1;
     tSelector.setUnitIncrement(1);
     tSelector.setBlockIncrement(blockIncrement);
   }
 }
  private final void invertGray8Stack(ImageStack image) {
    int sizeX = image.getWidth();
    int sizeY = image.getHeight();
    int sizeZ = image.getSize();

    for (int z = 0; z < sizeZ; z++) {
      for (int y = 0; y < sizeY; y++) {
        for (int x = 0; x < sizeX; x++) {
          image.setVoxel(x, y, z, 255 - image.getVoxel(x, y, z));
        }
      }
    }
  }
  /** 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 #20
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 #21
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 #22
0
 public boolean showDialog(ImageStack stack) {
   hyperstack = imp.isHyperStack();
   boolean showCheckbox = false;
   if (hyperstack && imp.getNSlices() > 1 && imp.getNFrames() > 1) showCheckbox = true;
   else if (hyperstack && imp.getNSlices() > 1) reduceSlices = true;
   int n = stack.getSize();
   GenericDialog gd = new GenericDialog("Reduce Size");
   gd.addNumericField("Reduction Factor:", factor, 0);
   if (showCheckbox) gd.addCheckbox("Reduce in Z-Dimension", false);
   gd.showDialog();
   if (gd.wasCanceled()) return false;
   factor = (int) gd.getNextNumber();
   if (showCheckbox) reduceSlices = gd.getNextBoolean();
   return true;
 }
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();
 }
  void borderstack(final ImageStack stack1, int nb, byte[] b) {
    final AtomicInteger ai = new AtomicInteger(0);
    final int dimX = stack1.getWidth();
    final int dimY = stack1.getHeight();
    final int dimZ = stack1.getSize();
    final byte[][] bord = new byte[dimZ][nb];

    for (int ithread = 0; ithread < threads.length; ithread++) {

      // Concurrently run in as many threads as CPUs

      threads[ithread] =
          new Thread() {

            public void run() {
              for (int superi = ai.getAndIncrement();
                  superi < dimZ;
                  superi = ai.getAndIncrement()) {
                int k = superi;
                ImageProcessor ip = stack1.getProcessor(k + 1);
                for (int j = 0; j < dimY; j++) {
                  for (int i = 0; i < dimX; i++) {
                    int val = (int) (ip.getPixelValue(i, j));
                    if ((val != 0)
                        && (i == 0
                            || j == 0
                            || k == 0
                            || i == dimX - 1
                            || j == dimY - 1
                            || k == dimZ - 1))
                      // bord[k][val-2]=1;
                      bord[k][val - 1] = 1;
                  }
                }
              }
            }
          };
    }
    startAndJoin(threads);
    for (int i = 0; i < dimZ; i++) {
      for (int j = 0; j < nb; j++) {
        b[j] *= (1 - bord[i][j]);
      }
    }
    for (int j = 0; j < nb; j++) {
      b[j] = (byte) (1 - b[j]);
    }
  }
Exemple #25
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);
 }
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;
 }
  /**
   * Constructor that builds up a VectorProcessor froma a stack of {@link FloatProcessor}s This is
   * the constructor that is being used in @link{KMeans}
   *
   * @param stack a stack of {@link FloatProcessor}s.
   */
  public VectorProcessor(final ImageStack stack) {
    /* Calls the constructor
    @link{VectorProcessor(final int width, final int height, final int numberOfValues)}*/
    this(stack.getWidth(), stack.getHeight(), stack.getSize());

    /* Gets the images in the stack and puts them into an array of Object*/
    final Object[] slices = stack.getImageArray();
    /* For each image (= component) in the stack */
    for (int i = 0; i < numberOfValues; ++i) {
      /* get the pixels as an array of float */
      final float[] values = (float[]) slices[i];
      /* for each pixel */
      for (int j = 0; j < values.length; j++) {
        /* store the value */
        pixels[j][i] = values[j];
      }
    }
  }
Exemple #28
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;
   }
 }
Exemple #29
0
 public CompositeImage(ImagePlus imp, int mode) {
   if (mode < COMPOSITE || mode > GRAYSCALE) mode = COLOR;
   this.mode = mode;
   int channels = imp.getNChannels();
   bitDepth = getBitDepth();
   if (IJ.debugMode) IJ.log("CompositeImage: " + imp + " " + mode + " " + channels);
   ImageStack stack2;
   boolean isRGB = imp.getBitDepth() == 24;
   if (isRGB) {
     if (imp.getImageStackSize() > 1)
       throw new IllegalArgumentException("RGB stacks not supported");
     stack2 = getRGBStack(imp);
   } else stack2 = imp.getImageStack();
   int stackSize = stack2.getSize();
   if (channels == 1 && isRGB) channels = 3;
   if (channels == 1 && stackSize <= MAX_CHANNELS && !imp.dimensionsSet) channels = stackSize;
   if (channels < 1 || (stackSize % channels) != 0)
     throw new IllegalArgumentException("stacksize not multiple of channels");
   if (mode == COMPOSITE && channels > MAX_CHANNELS) this.mode = COLOR;
   compositeImage = true;
   int z = imp.getNSlices();
   int t = imp.getNFrames();
   if (channels == stackSize || channels * z * t != stackSize)
     setDimensions(channels, stackSize / channels, 1);
   else setDimensions(channels, z, t);
   setStack(imp.getTitle(), stack2);
   setCalibration(imp.getCalibration());
   FileInfo fi = imp.getOriginalFileInfo();
   if (fi != null) {
     displayRanges = fi.displayRanges;
     channelLuts = fi.channelLuts;
   }
   setFileInfo(fi);
   Object info = imp.getProperty("Info");
   if (info != null) setProperty("Info", imp.getProperty("Info"));
   if (mode == COMPOSITE) {
     for (int i = 0; i < MAX_CHANNELS; i++) active[i] = true;
   } else active[0] = true;
   // if (!(channels==3&&stackSize==3))
   setRoi(imp.getRoi());
   setOverlay(imp.getOverlay());
   if (channels != stackSize) setOpenAsHyperStack(true);
 }
  private ImageStack createInvertedLeveledCubeGraphImage() {
    ImageStack stack = createCubeGraphImage();
    for (int z = 0; z < stack.getSize(); z++) {
      for (int y = 0; y < stack.getHeight(); y++) {
        for (int x = 0; x < stack.getWidth(); x++) {
          stack.setVoxel(x, y, z, 255 - stack.getVoxel(x, y, z));
        }
      }
    }
    stack.setVoxel(5, 1, 1, 32);
    stack.setVoxel(9, 5, 1, 64);
    stack.setVoxel(9, 9, 5, 96);
    stack.setVoxel(9, 5, 9, 128);
    stack.setVoxel(5, 1, 9, 160);
    stack.setVoxel(1, 5, 9, 192);
    stack.setVoxel(1, 9, 5, 224);

    return stack;
  }