Esempio n. 1
0
  /**
   * Calculate the Rand index between some 2D original labels and the corresponding proposed labels.
   * Both image are binarized. We follow the definition of 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 label 2D image with the original labels
   * @param proposal 2D image with the proposed labels
   * @param binaryThreshold threshold value to binarize the input images
   * @return rand index value and derived statistics
   */
  public ClassificationStatistics randIndexStats(
      ImageProcessor label, ImageProcessor proposal, double binaryThreshold) {
    // Binarize inputs
    ByteProcessor binaryLabel = new ByteProcessor(label.getWidth(), label.getHeight());
    ByteProcessor binaryProposal = new ByteProcessor(label.getWidth(), label.getHeight());

    for (int x = 0; x < label.getWidth(); x++)
      for (int y = 0; y < label.getHeight(); y++) {
        binaryLabel.set(x, y, label.getPixelValue(x, y) > binaryThreshold ? 255 : 0);
        binaryProposal.set(x, y, proposal.getPixelValue(x, y) > binaryThreshold ? 255 : 0);
      }

    // Find components
    ShortProcessor components1 =
        (ShortProcessor)
            Utils.connectedComponents(new ImagePlus("binary labels", binaryLabel), 4)
                .allRegions
                .getProcessor();

    ShortProcessor components2 =
        (ShortProcessor)
            Utils.connectedComponents(new ImagePlus("proposal labels", binaryProposal), 4)
                .allRegions
                .getProcessor();

    return getRandIndexStats(components1, components2);
  }
Esempio n. 2
0
  protected static final FloatProcessor scaleByte(final ByteProcessor bp) {
    final FloatProcessor fp = new FloatProcessor(bp.getWidth(), bp.getHeight());
    final byte[] bytes = (byte[]) bp.getPixels();
    final float[] floats = (float[]) fp.getPixels();
    for (int i = 0; i < bytes.length; ++i) floats[i] = (bytes[i] & 0xff) / 255.0f;

    return fp;
  }
Esempio n. 3
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);
  }
Esempio n. 4
0
 /** Produce a binary image based on the current confidence matrix */
 private void createBinaryMask() {
   if (null != confMatrix) {
     final ByteProcessor result = (ByteProcessor) confMatrix.convertToByte(false);
     result.multiply(255);
     // Set background color based on the Process > Binary > Options
     if (!Prefs.blackBackground) result.invert();
     new ImagePlus("Mask", result).show();
   }
 }
Esempio n. 5
0
 private void calculateGreyValues() {
   int size = image.getPixelCount();
   int gray;
   for (int pos = 0; pos < size; pos++) {
     gray = image.get(pos);
     grayValue[pos] = (byte) (gray / GRAY_SCALE); // quantized for texture analysis
     grayHistogram[gray]++;
   }
   Arrays2.div(grayHistogram, size);
 }
  /**
   * Retrieve byte data of 8 bits image
   *
   * @param imp : image to analyze
   * @return byte array with data for each pixel
   */
  public static byte[] getByteData(ImagePlus imp) {
    byte[] imagebyte = null;
    for (int i = 0; i < imp.getStackSize(); i++) {
      ByteProcessor fp = (ByteProcessor) imp.getImageStack().getProcessor(i + 1).duplicate();
      if (i == 0) imagebyte = (byte[]) fp.getPixels();
      else
        imagebyte =
            concatByte(imagebyte, (byte[]) fp.getPixels()); // (byte[]) ArrayUtils.addAll(imagebyte,
      // (byte[])fp.getPixels());
      System.out.println("slice : " + (i + 1) + "/" + imp.getStackSize());
    }

    return imagebyte;
  }
Esempio n. 7
0
 void doIterations(ImageProcessor ip, String mode) {
   if (escapePressed) return;
   if (!previewing && iterations > 1) IJ.showStatus(arg + "... press ESC to cancel");
   for (int i = 0; i < iterations; i++) {
     if (Thread.currentThread().isInterrupted()) return;
     if (IJ.escapePressed()) {
       escapePressed = true;
       ip.reset();
       return;
     }
     if (mode.equals("erode")) ((ByteProcessor) ip).erode(count, background);
     else ((ByteProcessor) ip).dilate(count, background);
   }
 }
Esempio n. 8
0
  public void run(ImageProcessor image) {
    /**
     * ********************************************************************************* Initial
     * phase *********************************************************************************
     */
    int width = image.getWidth();
    int heigh = image.getHeight();
    ByteProcessor bp = Service.getByteProcessor(image);

    /**
     * ********************************************************************************* Convolve
     * with LoG kernel
     * *********************************************************************************
     */
    Convolver convolver = new Convolver();
    convolver.setNormalize(false);
    convolver.convolve(bp, log, (int) Math.sqrt(log.length), (int) Math.sqrt(log.length));
    ImagePlus outImg = new ImagePlus("Later Log kernel", bp);
    outImg.show();

    /**
     * ********************************************************************************* threshold
     * *********************************************************************************
     */
    ByteProcessor bpThreshold = Service.getByteProcessor(bp);
    int lut[] = new int[256];
    int i = 0;
    for (; i < threshold; i++) lut[i] = 0;
    for (int j = i; j < lut.length; j++) lut[j] = 255;
    bpThreshold.applyTable(lut);
    ImagePlus outImg1 = new ImagePlus("Later threshold phase", bpThreshold);
    outImg1.show();

    /**
     * ********************************************************************************* Find Zero
     * crossing *********************************************************************************
     */
    ByteProcessor out = new ByteProcessor(width, heigh);
    for (i = 0; i < width; i++) for (int j = 0; j < heigh; j++) out.set(i, j, 255);
    for (int x = 0; x < width - 1; x++) {
      for (int y = 0; y < heigh - 1; y++) {
        if (bpThreshold.get(x, y) != bpThreshold.get(x, y + 1)) out.set(x, y, 0);
        if (bpThreshold.get(x, y) != bpThreshold.get(x + 1, y)) out.set(x, y, 0);
        if (bpThreshold.get(x, y) != bpThreshold.get(x + 1, y + 1)) out.set(x, y, 0);
      }
    }
    ImagePlus outImg2 = new ImagePlus("Edge Find", out);
    outImg2.show();
  }
Esempio n. 9
0
  public GrayLevelClass(ByteProcessor img, boolean first) {
    if (!probabilityHistogramDone) {
      int[] histogram = img.getHistogram();
      probabilityHistogram = new float[256];

      for (int i = 0; i < 256; i++) {
        probabilityHistogram[i] = ((float) histogram[i]) / ((float) N);
        // IJ.write(" "+probabilityHistogram[i]);
      }
      probabilityHistogramDone = true;
    }

    if (first) {
      index = 1;
      omega = probabilityHistogram[index - 1];
      if (omega == 0) mu = 0;
      else mu = 1 * probabilityHistogram[index - 1] / omega;
    } else {
      index = 2;
      omega = 0;
      mu = 0;
      for (int i = index; i < 256; i++) {
        omega += probabilityHistogram[i - 1];
        mu += probabilityHistogram[i - 1] * i;
      }
      if (omega == 0) mu = 0;
      else mu /= omega;
    }
  }
Esempio n. 10
0
 void skeletonize(ImageProcessor ip) {
   if (Prefs.blackBackground) ip.invert();
   boolean edgePixels = hasEdgePixels(ip);
   ImageProcessor ip2 = expand(ip, edgePixels);
   ((ByteProcessor) ip2).skeletonize();
   ip = shrink(ip, ip2, edgePixels);
   if (Prefs.blackBackground) ip.invert();
 }
Esempio n. 11
0
  private void calculate() {
    calculateGreyValues();

    final int imageWidth = image.getWidth();
    final int imageHeight = image.getHeight();
    final int d = HARALICK_DIST;
    int i, j, pos;

    // image is not empty per default
    for (int y = 0; y < imageHeight; y++) {
      for (int x = 0; x < imageWidth; x++) {
        pos = imageWidth * y + x;

        // horizontal neighbor: 0 degrees
        i = x - d;
        //                j = y;
        if (!(i < 0)) {
          increment(grayValue[pos], grayValue[pos - d]);
        }

        // vertical neighbor: 90 degree
        //                i = x;
        j = y - d;
        if (!(j < 0)) {
          increment(grayValue[pos], grayValue[pos - d * imageWidth]);
        }

        // 45 degree diagonal neigbor
        i = x + d;
        j = y - d;
        if (i < imageWidth && !(j < 0)) {
          increment(grayValue[pos], grayValue[pos + d - d * imageWidth]);
        }

        // 135 vertical neighbor
        i = x - d;
        j = y - d;
        if (!(i < 0) && !(j < 0)) {
          increment(grayValue[pos], grayValue[pos - d - d * imageWidth]);
        }
      }
    }
    meanGrayValue = Arrays2.sum(grayValue);
  }
Esempio n. 12
0
 public Coocurrence(ByteProcessor b, int numGrayValues, int haralickDist) {
   this.NUM_GRAY_VALUES = numGrayValues;
   this.image = b;
   this.GRAY_SCALE = (double) GRAY_RANGES / (double) NUM_GRAY_VALUES;
   this.cooccurrenceMatrices = new double[NUM_GRAY_VALUES][NUM_GRAY_VALUES];
   this.grayValue = new byte[image.getPixelCount()];
   this.grayHistogram = new double[GRAY_RANGES];
   this.HARALICK_DIST = haralickDist;
   calculate();
 }
  @Test
  public final void testDistanceMap_ChessBoard() {
    ByteProcessor image = new ByteProcessor(12, 10);
    image.setBackgroundValue(0);
    image.setValue(0);
    image.fill();
    for (int y = 2; y < 8; y++) {
      for (int x = 2; x < 10; x++) {
        image.set(x, y, 255);
      }
    }

    short[] weights = ChamferWeights.CHESSBOARD.getShortWeights();
    DistanceTransform5x5Short algo = new DistanceTransform5x5Short(weights, true);
    ImageProcessor result = algo.distanceMap(image);

    assertNotNull(result);
    assertEquals(image.getWidth(), result.getWidth());
    assertEquals(image.getHeight(), result.getHeight());
    assertEquals(3, result.get(4, 4));
  }
  @Test
  public final void testDistanceMap_UntilCorners_Weights23() {
    ByteProcessor image = new ByteProcessor(7, 7);
    image.setValue(255);
    image.fill();
    image.set(4, 4, 0);

    short[] weights = ChamferWeights.WEIGHTS_23.getShortWeights();
    DistanceTransform5x5Short algo = new DistanceTransform5x5Short(weights, false);
    ImageProcessor result = algo.distanceMap(image);

    assertNotNull(result);
    assertEquals(image.getWidth(), result.getWidth());
    assertEquals(image.getHeight(), result.getHeight());
    assertEquals(12, result.get(0, 0));
    assertEquals(10, result.get(6, 0));
    assertEquals(10, result.get(0, 6));
    assertEquals(6, result.get(6, 6));

    assertEquals(9, result.get(0, 5));
  }
  /** Another test for chessknight weigths, to fix a bug that incorrectly checked image bounds. */
  @Test
  public final void testDistanceMap_UntilCorners_ChessKnight2() {
    ByteProcessor image = new ByteProcessor(9, 9);
    image.setValue(255);
    image.fill();
    image.set(6, 6, 0);

    short[] weights = ChamferWeights.CHESSKNIGHT.getShortWeights();
    DistanceTransform5x5Short algo = new DistanceTransform5x5Short(weights, false);
    ImageProcessor result = algo.distanceMap(image);

    assertNotNull(result);
    assertEquals(image.getWidth(), result.getWidth());
    assertEquals(image.getHeight(), result.getHeight());
    assertEquals(42, result.get(0, 0));
    assertEquals(32, result.get(8, 0));
    assertEquals(32, result.get(0, 8));
    assertEquals(14, result.get(8, 8));

    assertEquals(30, result.get(0, 6));
  }
  /**
   * Create ImagePlusExtended object from primary array (byte, short ....)
   *
   * @param title : title of the image
   * @param object : array
   * @param showImage : display image if true
   * @return ImagePlusExtended
   */
  public static ImagePlusExtended createImage(String title, Object object, boolean showImage) {
    ImagePlusExtended imp = null;
    int i = 0;
    if (object instanceof byte[][]) {
      byte[][] is = (byte[][]) object;
      int height = is.length;
      int width = is[0].length;
      ByteProcessor byteprocessor = new ByteProcessor(width, height);
      byte[] bp = (byte[]) byteprocessor.getPixels();
      int h = 0;
      while (h < height) {
        int w = 0;
        while (w < width) {
          bp[i] = is[h][w];
          w++;
          i++;
        }
        i = ++h * width;
      }
      imp = new ImagePlusExtended(title, byteprocessor);

    } else if (object instanceof short[][]) {
      short[][] is = (short[][]) object;
      int height = is.length;
      int width = is[0].length;
      ShortProcessor shortprocessor = new ShortProcessor(width, height);
      short[] sp = (short[]) shortprocessor.getPixels();
      int h = 0;
      while (h < height) {
        int w = 0;
        while (w < width) {
          sp[i] = is[h][w];
          w++;
          i++;
        }
        i = ++h * width;
      }
      imp = new ImagePlusExtended(title, shortprocessor);

    } else if (object instanceof int[][]) {
      int[][] is = (int[][]) object;
      int height = is.length;
      int width = is[0].length;
      ShortProcessor shortprocessor = new ShortProcessor(width, height);
      short[] sp = (short[]) shortprocessor.getPixels();
      int h = 0;
      while (h < height) {
        int w = 0;
        while (w < width) {
          sp[i] = (short) is[h][w];
          w++;
          i++;
        }
        i = ++h * width;
      }
      imp = new ImagePlusExtended(title, shortprocessor);
    } else if (object instanceof float[][]) {
      float[][] fs = (float[][]) object;
      int height = fs.length;
      int width = fs[0].length;
      FloatProcessor floatprocessor = new FloatProcessor(width, height);
      float[] fp = (float[]) floatprocessor.getPixels();
      int h = 0;
      while (h < height) {
        int w = 0;
        while (w < width) {
          fp[i] = fs[h][w];
          w++;
          i++;
        }
        i = ++h * width;
      }
      floatprocessor.resetMinAndMax();
      imp = new ImagePlusExtended(title, floatprocessor);

    } else if (object instanceof double[][]) {
      double[][] ds = (double[][]) object;
      int height = ds.length;
      int width = ds[0].length;
      FloatProcessor floatprocessor = new FloatProcessor(width, height);
      float[] fp = (float[]) floatprocessor.getPixels();
      int h = 0;
      while (h < height) {
        int w = 0;
        while (w < width) {
          fp[i] = (float) ds[h][w];
          w++;
          i++;
        }
        i = ++h * width;
      }
      floatprocessor.resetMinAndMax();
      imp = new ImagePlusExtended(title, floatprocessor);

    } else if (object instanceof byte[][][]) {
      byte[][][] is = (byte[][][]) object;
      int height = is.length;
      int width = is[0].length;
      int stackSize = is[0][0].length;
      ImageStack imagestack = new ImageStack(width, height);
      for (int sz = 0; sz < stackSize; sz++) {
        ByteProcessor byteprocessor = new ByteProcessor(width, height);
        byte[] bp = (byte[]) byteprocessor.getPixels();
        i = 0;
        int h = 0;
        while (h < height) {
          int w = 0;
          while (w < width) {
            bp[i] = is[h][w][sz];
            w++;
            i++;
          }
          i = ++h * width;
        }
        imagestack.addSlice("", byteprocessor);
      }
      imp = new ImagePlusExtended(title, imagestack);

    } else if (object instanceof short[][][]) {
      short[][][] is = (short[][][]) object;
      int height = is.length;
      int width = is[0].length;
      int stackSize = is[0][0].length;
      ImageStack imagestack = new ImageStack(width, height);
      for (int sz = 0; sz < stackSize; sz++) {
        ShortProcessor shortprocessor = new ShortProcessor(width, height);
        short[] sp = (short[]) shortprocessor.getPixels();
        i = 0;
        int h = 0;
        while (h < height) {
          int w = 0;
          while (w < width) {
            sp[i] = is[h][w][sz];
            w++;
            i++;
          }
          i = ++h * width;
        }
        imagestack.addSlice("", shortprocessor);
      }
      imp = new ImagePlusExtended(title, imagestack);

    } else if (object instanceof int[][][]) {
      int[][][] is = (int[][][]) object;
      int height = is.length;
      int width = is[0].length;
      int stackSize = is[0][0].length;
      ImageStack imagestack = new ImageStack(width, height);
      for (int sz = 0; sz < stackSize; sz++) {
        ShortProcessor shortprocessor = new ShortProcessor(width, height);
        short[] sp = (short[]) shortprocessor.getPixels();
        i = 0;
        int h = 0;
        while (h < height) {
          int w = 0;
          while (w < width) {
            sp[i] = (short) is[h][w][sz];
            w++;
            i++;
          }
          i = ++h * width;
        }
        if (sz == 0) shortprocessor.resetMinAndMax();
        imagestack.addSlice("", shortprocessor);
      }
      imp = new ImagePlusExtended(title, imagestack);

    } else if (object instanceof float[][][]) {
      float[][][] fs = (float[][][]) object;
      int height = fs.length;
      int width = fs[0].length;
      int stackSize = fs[0][0].length;
      ImageStack imagestack = new ImageStack(width, height);
      for (int sz = 0; sz < stackSize; sz++) {
        FloatProcessor floatprocessor = new FloatProcessor(width, height);
        float[] fp = (float[]) floatprocessor.getPixels();
        i = 0;
        int h = 0;
        while (h < height) {
          int w = 0;
          while (w < width) {
            fp[i] = fs[h][w][sz];
            w++;
            i++;
          }
          i = ++h * width;
        }
        if (sz == 0) floatprocessor.resetMinAndMax();
        imagestack.addSlice("", floatprocessor);
      }
      imp = new ImagePlusExtended(title, imagestack);

    } else if (object instanceof double[][][]) {
      double[][][] ds = (double[][][]) object;
      int height = ds.length;
      int width = ds[0].length;
      int stackSize = ds[0][0].length;
      ImageStack imagestack = new ImageStack(width, height);
      for (int sz = 0; sz < stackSize; sz++) {
        FloatProcessor floatprocessor = new FloatProcessor(width, height);
        float[] fp = (float[]) floatprocessor.getPixels();
        i = 0;
        int h = 0;
        while (h < height) {
          int w = 0;
          while (w < width) {
            fp[i] = (float) ds[h][w][sz];
            w++;
            i++;
          }
          i = ++h * width;
        }
        if (sz == 0) floatprocessor.resetMinAndMax();
        imagestack.addSlice("", floatprocessor);
      }
      imp = new ImagePlusExtended(title, imagestack);

    } else {
      System.out.println("MIJ Error message: Unknow type of images or volumes.");
      return null;
    }

    if (showImage) {
      imp.show();
      imp.updateAndDraw();
    }
    return imp;
  }
Esempio n. 17
0
 void outline(ImageProcessor ip) {
   if (Prefs.blackBackground) ip.invert();
   ((ByteProcessor) ip).outline();
   if (Prefs.blackBackground) ip.invert();
 }
Esempio n. 18
0
  public void run(ImageProcessor ip) {
    ImageUtils.initMMorph4J();

    if (ip instanceof ByteProcessor) {
      GrayScaleImage img = ImageJAdapter.toGrayScaleImage((ByteProcessor) ip);

      Object obj[] = BuilderTreeOfShapeByUnionFindParallel.getImageInterpolate(img);
      short interpolation0[] = (short[]) obj[0];
      short interpolation1[] = (short[]) obj[1];

      int interpWidth = (img.getWidth() * 4 - 3);
      int interpHeight = (img.getHeight() * 4 - 3);

      ByteProcessor imgOut0 = new ByteProcessor(interpWidth, interpHeight);
      ByteProcessor imgOut1 = new ByteProcessor(interpWidth, interpHeight);

      for (int i = 0; i < interpolation0.length; i++) {
        // imgOut.setPixel(i, (interpolation0[i] + interpolation1[i]) / 2);
        imgOut0.set(i, (interpolation0[i] & 0xFF));
        imgOut1.set(i, (interpolation1[i] & 0xFF));
      }

      ImagePlus imgPlus0 = new ImagePlus("interpolation - max", imgOut0);
      imgPlus0.show("image interpolation - max");
      ImagePlus imgPlus1 = new ImagePlus("interpolation - min", imgOut1);
      imgPlus1.show("image interpolation - min");
    } else if (ip instanceof ColorProcessor) {
      ColorImage img = ImageJAdapter.toColorImage((ColorProcessor) ip);

      int interpWidth = (img.getWidth() * 4 - 3);
      int interpHeight = (img.getHeight() * 4 - 3);

      GrayScaleImage imgR = img.getRed();
      GrayScaleImage imgG = img.getGreen();
      GrayScaleImage imgB = img.getBlue();

      ColorProcessor imgOut0 = new ColorProcessor(interpWidth, interpHeight);
      ColorProcessor imgOut1 = new ColorProcessor(interpWidth, interpHeight);

      Object objR[] = BuilderTreeOfShapeByUnionFindParallel.getImageInterpolate(imgR);
      short interpolation0R[] = (short[]) objR[0];
      short interpolation1R[] = (short[]) objR[1];

      Object objG[] = BuilderTreeOfShapeByUnionFindParallel.getImageInterpolate(imgG);
      short interpolation0G[] = (short[]) objG[0];
      short interpolation1G[] = (short[]) objG[1];

      Object objB[] = BuilderTreeOfShapeByUnionFindParallel.getImageInterpolate(imgB);
      short interpolation0B[] = (short[]) objB[0];
      short interpolation1B[] = (short[]) objB[1];

      for (int i = 0; i < interpolation0R.length; i++) {

        int valor0 =
            ((0 & 0xFF) << 24)
                | ((interpolation0R[i] & 0xFF) << 16)
                | ((interpolation0G[i] & 0xFF) << 8)
                | ((interpolation0B[i] & 0xFF) << 0);

        imgOut0.set(i, valor0);

        int valor1 =
            ((0 & 0xFF) << 24)
                | ((interpolation1R[i] & 0xFF) << 16)
                | ((interpolation1G[i] & 0xFF) << 8)
                | ((interpolation1B[i] & 0xFF) << 0);
        imgOut1.set(i, valor1);
      }

      ImagePlus imgPlus0 = new ImagePlus("interpolation - max", imgOut0);
      imgPlus0.show("image interpolation - max");
      ImagePlus imgPlus1 = new ImagePlus("interpolation - min", imgOut1);
      imgPlus1.show("image interpolation - min");
    }
  }
Esempio n. 19
0
  // Particle finding routine based on spots enhancement with
  // 2D PSF Gaussian approximated convolution/backgrounds subtraction, thresholding
  // and particle filtering
  void detectParticles(
      ImageProcessor ip, SMLDialog fdg, int nFrame, Overlay SpotsPositions_, Roi RoiActive_) {
    int nThreshold;
    FloatProcessor dupip = null; // duplicate of image
    ImageProcessor dushort; // duplicate of image
    ByteProcessor dubyte = null; // tresholded image
    TypeConverter tc;

    dupip = (FloatProcessor) ip.duplicate().convertToFloat();

    SMLblur1Direction(
        dupip, fdg.dPSFsigma * 0.5, 0.0002, true, (int) Math.ceil(5 * fdg.dPSFsigma * 0.5));
    SMLblur1Direction(dupip, fdg.dPSFsigma * 0.5, 0.0002, false, 0);

    // new ImagePlus("gassconvoluted", dupip.convertToFloat().duplicate()).show();
    // low-pass filtering by gaussian blurring
    // lowpassGauss.blurGaussian(dupip, fdg.dPSFsigma*0.5, fdg.dPSFsigma*0.5, 0.0002);

    // convolution with gaussian PSF kernel
    SMLconvolveFloat(dupip, fConKernel, fdg.nKernelSize, fdg.nKernelSize);

    // new ImagePlus("convoluted", dupip.duplicate()).show();
    tc = new TypeConverter(dupip, true);
    dushort = tc.convertToShort();
    // new ImagePlus("convoluted", dushort.duplicate()).show();

    // thresholding

    // old straightforward thresholding
    // imgstat = ImageStatistics.getStatistics(dupip, 22, null); //6 means MEAN + STD_DEV, look at
    // ij.measure.Measurements
    // nThreshold = (int)(imgstat.mean + 3.0*imgstat.stdDev);

    // new smart thresholding
    nThreshold = getThreshold(dushort);

    dushort.threshold(nThreshold);
    // convert to byte
    dubyte = (ByteProcessor) dushort.convertToByte(false);
    // new ImagePlus("threshold", dubyte.duplicate()).show();

    // morphological operations on thresholded image
    // dubyte.dilate(2, 0);
    // dubyte.erode(2, 0);

    // cleaning up image a bit
    if (fdg.nKernelSize > 3) {
      dubyte.dilate();
      // new ImagePlus("dilated", dubyte.duplicate()).show();
      dubyte.erode();
      // new ImagePlus("erosion", dubyte.duplicate()).show();
    }
    // dupip.invert();

    labelParticles(
        dubyte,
        ip,
        nFrame,
        fdg.dPixelSize,
        fdg.nAreaCut,
        fdg.dPSFsigma,
        SpotsPositions_,
        fdg.bShowParticles,
        RoiActive_); // , fdg.bIgnoreFP);//, fdg.dSymmetry/100);
  }
  // -----------------------------------------------------------------------------------
  public void Lipschitz2D(ImageProcessor ip) {
    int slope, slope1, p, p1, p2, p3, p4, maxz;

    m_roi = ip.getRoi();
    ImageHeight = ip.getHeight();
    ImageWidth = ip.getWidth();
    m_channels = ip instanceof ColorProcessor ? 3 : 1;
    m_short = ip instanceof ShortProcessor;
    pixel = new int[m_channels];

    int[][] destPixels = new int[m_channels][ImageHeight * ImageWidth];
    int[][] srcPixels = new int[m_channels][ImageHeight * ImageWidth];
    byte[][] tmpBytePixels = new byte[m_channels][ImageHeight * ImageWidth];
    short[][] tmpShortPixels = new short[m_channels][ImageHeight * ImageWidth];

    if (m_channels == 1) {
      if (m_short) {
        tmpShortPixels[0] = (short[]) ip.getPixels();
      } else {
        tmpBytePixels[0] = (byte[]) ip.getPixels();
      }

    } else {
      ColorProcessor cip = (ColorProcessor) ip;
      cip.getRGB(tmpBytePixels[0], tmpBytePixels[1], tmpBytePixels[2]);
    }

    int sign = (m_Down ? 1 : -1);
    int topdown = (m_Down ? 0 : 255);
    for (int ii = 0; ii < m_channels; ii++) {
      for (int ij = 0; ij < ImageHeight * ImageWidth; ij++) {
        srcPixels[ii][ij] =
            (m_short
                ? sign * (tmpShortPixels[ii][ij] & 0xffff)
                : sign * (tmpBytePixels[ii][ij] & 0xff));
        destPixels[ii][ij] = srcPixels[ii][ij];
      }
    }

    slope = (int) (m_Slope);
    slope1 = (int) (slope * Math.sqrt(2.0));
    maxz = m_channels;

    for (int y = m_roi.y; y < m_roi.y + m_roi.height; y++) // rows
    {
      IJ.showProgress(y, 2 * ImageHeight);
      for (int z = 0; z < m_channels; z++) {
        p2 = sign * (topdown + (sign) * slope);
        p3 = sign * (topdown + (sign) * slope1);
        for (int x = m_roi.x; x < m_roi.x + m_roi.width; x++) // columns
        {
          p = (p2 - slope);
          p1 = (p3 - slope1);
          if (p1 > p) p = p1;
          p3 = destPixels[z][x + ImageWidth * (Math.max(y - 1, 0))];
          p1 = p3 - slope;
          if (p1 > p) p = p1;

          p4 = destPixels[z][Math.min(x + 1, ImageWidth - 1) + ImageWidth * (Math.max(y - 1, 0))];
          p1 = p4 - slope1;
          if (p1 > p) p = p1;

          p2 = srcPixels[z][x + ImageWidth * y];
          if (p > p2) {
            destPixels[z][x + ImageWidth * y] = p;
            p2 = p;
          }
        }
      }
    }

    for (int y = m_roi.y + m_roi.height - 1; y >= m_roi.y; y--) // rows
    {
      IJ.showProgress(2 * ImageHeight - y - 1, 2 * ImageHeight);
      for (int z = 0; z < maxz; z++) {
        p2 = sign * (topdown + (sign) * slope);
        p3 = sign * (topdown + (sign) * slope1);
        for (int x = m_roi.x + m_roi.width - 1; x >= m_roi.x; x--) // columns
        {
          p = (p2 - slope);
          p1 = (p3 - slope1);
          if (p1 > p) p = p1;

          p3 = destPixels[z][x + ImageWidth * (Math.min(y + 1, ImageHeight - 1))];
          p1 = p3 - slope;
          if (p1 > p) p = p1;

          p4 = destPixels[z][Math.max(x - 1, 0) + ImageWidth * (Math.min(y + 1, ImageHeight - 1))];
          p1 = p4 - slope1;
          if (p1 > p) p = p1;

          p2 = destPixels[z][x + ImageWidth * y];
          if (p > p2) {
            destPixels[z][x + ImageWidth * y] = p;
            p2 = p;
          }
        }
      }
    }

    for (int ii = 0; ii < m_channels; ii++) {
      for (int ij = 0; ij < ImageHeight * ImageWidth; ij++) {
        if (m_TopHat) {
          tmpBytePixels[ii][ij] =
              (m_Down
                  ? (byte) (srcPixels[ii][ij] - destPixels[ii][ij] + 255)
                  : (byte) (destPixels[ii][ij] - srcPixels[ii][ij]));
        } else {
          if (m_short) {
            tmpShortPixels[ii][ij] = (short) ((sign * destPixels[ii][ij] & 0xffff));
          } else {
            tmpBytePixels[ii][ij] = (byte) (sign * destPixels[ii][ij]);
          }
        }
      }
    }

    if (m_channels == 1) {
      if (m_short) {
        ShortProcessor sip = (ShortProcessor) ip;
        sip.setPixels(tmpShortPixels[0]);
      } else {
        ByteProcessor bip = (ByteProcessor) ip;
        bip.setPixels(tmpBytePixels[0]);
      }

    } else {
      ColorProcessor cip = (ColorProcessor) ip;
      cip.setRGB(tmpBytePixels[0], tmpBytePixels[1], tmpBytePixels[2]);
    }
  }
Esempio n. 21
0
  /** Called by the PlugInFilterRunner to process the image or one frame of a stack */
  public void run(ImageProcessor ip) {
    if (interrupted) return;
    int width = ip.getWidth();
    int height = ip.getHeight();

    int backgroundValue =
        (processType == VORONOI)
            ? (background255 ? 0 : (byte) 255)
            : // Voronoi needs EDM of the background
            (background255 ? (byte) 255 : 0); // all others do EDM of the foreground
    if (USES_WATERSHED[processType]) nPasses = 0; // watershed has its own progress bar
    FloatProcessor floatEdm = makeFloatEDM(ip, backgroundValue, false);

    ByteProcessor maxIp = null;
    if (USES_MAX_FINDER[processType]) {
      if (processType == VORONOI) floatEdm.multiply(-1); // Voronoi starts from minima of EDM
      int maxOutputType =
          USES_WATERSHED[processType] ? MaximumFinder.SEGMENTED : MaximumFinder.SINGLE_POINTS;
      boolean isEDM = processType != VORONOI;
      maxIp =
          maxFinder.findMaxima(
              floatEdm,
              MAXFINDER_TOLERANCE,
              ImageProcessor.NO_THRESHOLD,
              maxOutputType,
              false,
              isEDM);
      if (maxIp == null) { // segmentation cancelled by user?
        interrupted = true;
        return;
      } else if (processType != WATERSHED) {
        if (processType == VORONOI) floatEdm.multiply(-1);
        resetMasked(floatEdm, maxIp, processType == VORONOI ? -1 : 0);
      }
    }

    ImageProcessor outIp = null;
    if (processType == WATERSHED) {
      if (background255) maxIp.invert();
      ip.copyBits(maxIp, 0, 0, Blitter.COPY);
      ip.setBinaryThreshold();
    } else
      switch (outImageType) { // for all these, output contains the values of the EDM
        case FLOAT:
          outIp = floatEdm;
          break;
        case SHORT:
          floatEdm.setMinAndMax(0., 65535.);
          outIp = floatEdm.convertToShort(true);
          break;
        case BYTE:
          floatEdm.setMinAndMax(0., 255.);
          outIp = floatEdm.convertToByte(true);
          break;
        case BYTE_OVERWRITE:
          ip.setPixels(0, floatEdm);
          if (floatEdm.getMax() > 255.) ip.resetMinAndMax(); // otherwise we have max of floatEdm
      }

    if (outImageType != BYTE_OVERWRITE) { // new output image
      if (outStack == null) {
        outImp = new ImagePlus(TITLE_PREFIX[processType] + imp.getShortTitle(), outIp);
      } else outStack.setPixels(outIp.getPixels(), pfr.getSliceNumber());
    }
  } // public void run
  public void runStuff(
      DimensionMap map,
      TreeMap<DimensionMap, ROIPlus> maximaMap,
      TreeMap<DimensionMap, String> segMap,
      TreeMap<DimensionMap, String> maskMap,
      TreeMap<DimensionMap, String> imageMap,
      TreeMap<DimensionMap, Double> results,
      Canceler canceler) {
    // Get the Maxima
    ROIPlus maxima = maximaMap.get(map);

    // Make the mask image impMask
    // ByteProcessor impMask = (ByteProcessor) (new
    // ImagePlus(maskMap.get(map)).getProcessor().convertToByte(false));
    // ByteProcessor impSeg = (ByteProcessor) (new
    // ImagePlus(segMap.get(map)).getProcessor().convertToByte(false));
    ByteProcessor impSeg = (ByteProcessor) (new ImagePlus(segMap.get(map))).getProcessor();
    ByteProcessor impMask = (ByteProcessor) (new ImagePlus(maskMap.get(map))).getProcessor();
    ByteBlitter blit = new ByteBlitter(impSeg);
    blit.copyBits(impMask, 0, 0, Blitter.AND);
    FloatProcessor impImage =
        (FloatProcessor) (new ImagePlus(imageMap.get(map))).getProcessor().convertToFloat();
    Wand wand = new Wand(impSeg);
    Wand wand2 = new Wand(impMask);
    Vector<Double> measurements;
    for (IdPoint p : maxima.getPointList()) {
      if (canceler.isCanceled()) {
        return;
      }
      if (impSeg.getPixel(p.x, p.y)
          == 255) // if we land on a cell that made it through thresholding
      {
        wand.autoOutline(p.x, p.y); // outline it
        wand2.autoOutline(p.x, p.y);
        boolean partOfCellClump =
            !this.selectionsAreEqual(
                wand,
                wand2); // If the segmented and unsegmented masks do not agree on the roi, then this
        // cell is part of a clump.
        if (wand.npoints > 0) {
          Roi roi =
              new PolygonRoi(
                  wand.xpoints,
                  wand.ypoints,
                  wand.npoints,
                  Roi.POLYGON); // The roi helps for using getLength() (DON'T USE Roi.TRACED_ROI.,
          // IT SCREWS UP THE Polygon OBJECTS!!!! Bug emailed to ImageJ
          // folks)
          Polygon poly =
              new Polygon(
                  wand.xpoints,
                  wand.ypoints,
                  wand.npoints); // The polygon helps for using contains()
          Rectangle r = roi.getBounds();
          measurements = new Vector<Double>();
          for (int i = r.x; i < r.x + r.width; i++) {
            for (int j = r.y; j < r.y + r.height; j++) {
              // innerBoundary
              if (poly.contains(i, j) && impSeg.getPixelValue(i, j) == 255) {
                measurements.add((double) impImage.getPixelValue(i, j));
                // Logs.log("In - " + innerT, this);
              }
            }
          }

          impMask.setRoi(roi);
          ImageStatistics stats =
              ImageStatistics.getStatistics(
                  impMask,
                  ImageStatistics.AREA
                      & ImageStatistics.PERIMETER
                      & ImageStatistics.CIRCULARITY
                      & ImageStatistics.ELLIPSE,
                  null);
          if (measurements.size() > 0) {
            DimensionMap resultsMap = map.copy();
            resultsMap.put("Id", "" + p.id);

            resultsMap.put("Measurement", "X");
            results.put(resultsMap.copy(), (double) p.x);
            resultsMap.put("Measurement", "Y");
            results.put(resultsMap.copy(), (double) p.y);
            resultsMap.put("Measurement", "AREA");
            results.put(resultsMap.copy(), stats.area);
            resultsMap.put("Measurement", "PERIMETER");
            results.put(resultsMap.copy(), roi.getLength());
            resultsMap.put("Measurement", "CIRCULARITY");
            results.put(
                resultsMap.copy(), 4.0 * Math.PI * (stats.area / (Math.pow(roi.getLength(), 2))));
            resultsMap.put("Measurement", "ELLIPSE MAJOR");
            results.put(resultsMap.copy(), stats.major);
            resultsMap.put("Measurement", "ELLIPSE MINOR");
            results.put(resultsMap.copy(), stats.minor);
            resultsMap.put("Measurement", "MEAN");
            results.put(resultsMap.copy(), StatisticsUtility.mean(measurements));
            resultsMap.put("Measurement", "MEDIAN");
            results.put(resultsMap.copy(), StatisticsUtility.median(measurements));
            resultsMap.put("Measurement", "SUM");
            results.put(resultsMap.copy(), StatisticsUtility.sum(measurements));
            resultsMap.put("Measurement", "MIN");
            results.put(resultsMap.copy(), StatisticsUtility.min(measurements));
            resultsMap.put("Measurement", "MAX");
            results.put(resultsMap.copy(), StatisticsUtility.max(measurements));
            resultsMap.put("Measurement", "STDDEV");
            results.put(resultsMap.copy(), StatisticsUtility.stdDev(measurements));
            resultsMap.put("Measurement", "VARIANCE");
            results.put(resultsMap.copy(), StatisticsUtility.variance(measurements));
            resultsMap.put("Measurement", "CLUMP");
            results.put(resultsMap.copy(), (double) (partOfCellClump ? 1 : 0));
          }
        }
      }
    }
  }
Esempio n. 23
0
 public double getCooccurenceSums() {
   return image.getPixelCount() * 8;
 }