Java Code Examples for java.awt.image.WritableRaster#getSample()

The following examples show how to use java.awt.image.WritableRaster#getSample() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ImageUtils.java    From orbit-image-analysis with GNU General Public License v3.0 6 votes vote down vote up
/**
 * scales bands to min = 0 & max = 2^8 or 2^16
 *
 * @param image
 * @param min   int[] containing minima per band
 * @param max
 * @return
 */
public static BufferedImage scaleIntensities(BufferedImage image, int[] min, int[] max) throws IllegalArgumentException {
    WritableRaster raster = image.getRaster();

    if ((min.length != max.length) || min.length != raster.getNumBands())
        throw new IllegalArgumentException("Please ensure consistency of min and max arrays and number of bands in image");

    int width = image.getWidth();
    int height = image.getHeight();

    for (int row = 0; row < height; row++) {
        for (int col = 0; col < width; col++) {
            for (int band = 0; band < raster.getNumBands(); band++) {
                int pixel = raster.getSample(col, row, band);
                if (pixel < min[band]) pixel = min[band];
                if (pixel > max[band]) pixel = max[band];
                pixel = ((int) (((((double) pixel - min[band]) / (max[band] - min[band])) * ((int) Math.pow(2, image.getColorModel().getPixelSize()) - 1)) + 0.5));
                raster.setSample(col, row, band, pixel);
            }
        }
    }

    return image;
}
 
Example 2
Source File: ImageUtils.java    From orbit-image-analysis with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Calculates and returns band histograms of a BufferedImage
 *
 * @param image
 * @return
 */
public static int[][] getChannelHistograms(BufferedImage image) {
    WritableRaster raster = image.getRaster();
    int[][] histograms = new int[raster.getNumBands()][(int) (Math.pow(2, image.getColorModel().getPixelSize()) - 1)];

    int width = image.getWidth();
    int height = image.getHeight();

    for (int row = 0; row < height; row++) {
        for (int col = 0; col < width; col++) {
            for (int band = 0; band < raster.getNumBands(); band++) {
                histograms[band][raster.getSample(col, row, band)]++;
            }
        }
    }

    return histograms;
}
 
Example 3
Source File: ImageUtils.java    From orbit-image-analysis with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Calculates and returns band histograms of a BufferedImage w/o a need to extract the raster
 *
 * @param raster
 * @param width
 * @param height
 * @param iNumBins
 * @return
 */
public static int[][] getChannelHistograms(WritableRaster raster, int width, int height, int iNumBins) {

    int[][] histograms = new int[raster.getNumBands()][iNumBins];


    for (int row = 0; row < height; row++) {
        for (int col = 0; col < width; col++) {
            for (int band = 0; band < raster.getNumBands(); band++) {
                histograms[band][raster.getSample(col, row, band)]++;
            }
        }
    }

    return histograms;
}
 
Example 4
Source File: AverageHash.java    From MtgDesktopCompanion with GNU General Public License v3.0 6 votes vote down vote up
private static long hashChunk(BufferedImage chunk)
{
	WritableRaster r = chunk.getRaster();
	long hash = 0;
	int avg = 0;
	for(int x=0;x<8;x++)
	{
		for(int y=0;y<8;y++)
		{
			avg += r.getSample(x, y, 0);
		}
	}
	avg /= 64;
	for(int x=0;x<8;x++)
	{
		for(int y=0;y<8;y++)
		{
			if(r.getSample(x, y, 0)<avg)
			{
				hash |= 1;
			}
			hash<<=1;
		}
	}
	return hash;
}
 
Example 5
Source File: FeatureTiles.java    From geopackage-java with MIT License 6 votes vote down vote up
/**
 * Determine if the image is transparent
 *
 * @param image
 *            image
 * @return true if transparent
 */
protected boolean isTransparent(BufferedImage image) {
	boolean transparent = false;
	if (image != null) {
		WritableRaster raster = image.getAlphaRaster();
		if (raster != null) {
			transparent = true;
			done: for (int x = 0; x < image.getWidth(); x++) {
				for (int y = 0; y < image.getHeight(); y++) {
					if (raster.getSample(x, y, 0) > 0) {
						transparent = false;
						break done;
					}
				}
			}
		}
	}
	return transparent;
}
 
Example 6
Source File: ImageUtils.java    From orbit-image-analysis with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Can be used to verify impact of different encoding algorithms. Compares two BufferedImages and outputs differences between those.
 *
 * @param image
 * @param image2
 * @return
 */
public static int[] calculateBufferedImageDifferencesPxByPx(BufferedImage image, BufferedImage image2) {
    int width = image.getWidth();
    int height = image.getHeight();

    int width2 = image2.getWidth();
    int height2 = image2.getHeight();

    WritableRaster raster1 = image.getRaster();
    WritableRaster raster2 = image2.getRaster();

    if (width != width2 || height != height2)
        throw new IllegalArgumentException("Please insert two identical images that were treated with different image algorithms");

    int[] diff = new int[width * height];

    for (int row = 0; row < height; row++) {
        for (int col = 0; col < width; col++) {
            for (int band = 0; band < raster1.getNumBands(); band++) {
                int p1 = raster1.getSample(col, row, band);
                int p2 = raster2.getSample(col, row, band);

                diff[((row * width) + col)] = p2 - p1;
            }
        }
    }

    return diff;
}
 
Example 7
Source File: ImageUtil.java    From tess4j with Apache License 2.0 5 votes vote down vote up
/**
 * Whether the pixel is black.
 * 
 * @param image source image
 * @param x
 * @param y
 * @return 
 */
public static boolean isBlack(BufferedImage image, int x, int y) {
    if (image.getType() == BufferedImage.TYPE_BYTE_BINARY) {
        WritableRaster raster = image.getRaster();
        int pixelRGBValue = raster.getSample(x, y, 0);
        return pixelRGBValue == 0;
    }

    int luminanceValue = 140;
    return isBlack(image, x, y, luminanceValue);
}
 
Example 8
Source File: TestNDPINativeAndJava.java    From orbit-image-analysis with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Here we check that the NDPI Reader that uses Native libraries produces the
 * same results as the Java version (which uses Bioformats), using Brightfield
 * image as a test.
 * @throws Exception :-(
 */
@Ignore
@Test
public void testReaderIdenticalBrightfieldTilePixels() throws Exception {

    // Check the first and second levels.
    for(int i=0; i<2; i++) {
        OrbitTiledImage2 imgJava = getRecognitionFrameJava(TestImageType.BRIGHTFIELD, i).bimg.getImage();
        OrbitTiledImage2 imgNative = getRecognitionFrameNative(TestImageType.BRIGHTFIELD, i).bimg.getImage();

        // The images should have the same dimension irrespective of the reader used.
        assertEquals(imgJava.getWidth(), imgNative.getWidth());
        assertEquals(imgJava.getHeight(), imgNative.getHeight());

        // rJ has tile size of 512, and rN has tile size of 1024 - which is why tile coordinates are different in each case.
        WritableRaster rJ = (WritableRaster) imgJava.getTile(0, 0).createTranslatedChild(0, 0);
        WritableRaster rN = (WritableRaster) imgNative.getTile(0, 0).createTranslatedChild(0, 0);

        int pixelJ = rJ.getSample(rJ.getMinX() + rJ.getWidth() - 100, rJ.getMinY() + rJ.getHeight() - 100, 0);
        int pixelN = rN.getSample(rN.getMinX() + rN.getWidth() - 100, rN.getMinY() + rN.getHeight() - 100, 0);

        // 'Random' pixel values at the first tile should have the same value.
        assertEquals(pixelJ, pixelN, 1);

        // rJ has tile size of 512, and rN has tile size of 1024 - which is why tile coordinates are different in each case.
        WritableRaster rJ2 = (WritableRaster) imgJava.getTile(3, 4).createTranslatedChild(0, 0);
        WritableRaster rN2 = (WritableRaster) imgNative.getTile(7, 9).createTranslatedChild(0, 0);

        // A test that shouldn't suffer from: https://github.com/ome/bioformats/issues/3059
        int pixelJ2 = rJ2.getSample(rJ.getMinX() + rJ.getWidth() - 100, rJ.getMinY() + rJ.getHeight() - 8, 0);
        int pixelN2 = rN2.getSample(rN.getMinX() + rN.getWidth() - 100, rN.getMinY() + rN.getHeight() - 8, 0);

        // Pixels at the same place on the last tile should have the same value.
        assertEquals(pixelJ2, pixelN2, 1);

        // A test that should suffer from: https://github.com/ome/bioformats/issues/3059
        int pixelJ2a = rJ2.getSample(rJ.getMinX() + rJ.getWidth() - 100, rJ.getMinY() + rJ.getHeight()-1, 0);
        int pixelN2a = rN2.getSample(rN.getMinX() + rN.getWidth() - 100, rN.getMinY() + rN.getHeight()-1, 0);

        // Pixels at the same place on the last tile should have the same value.
        assertEquals(pixelJ2a, pixelN2a, 1);

        // Extract an area from the image (to avoid tile size differences)
        Rectangle rect = new Rectangle(imgJava.getWidth()-3456,imgJava.getHeight()-3456,1024,1024);
        WritableRaster rJ3 = (WritableRaster) imgJava.getData(rect).createTranslatedChild(0,0);
        WritableRaster rN3 = (WritableRaster) imgNative.getData(rect).createTranslatedChild(0,0);

        // Grab the first pixel
        int pixelJ3 = rJ3.getSample(0,0,0);
        int pixelN3 = rN3.getSample(0,0,0);

        assertEquals(pixelN3, pixelJ3,0);

        // Grab a more random pixel
        int pixelN4 = rN3.getSample(rN3.getMinX()+rN3.getWidth()-666, rN3.getMinY()+rN3.getHeight()-42,0);
        int pixelJ4 = rJ3.getSample(rJ3.getMinX()+rJ3.getWidth()-666, rJ3.getMinY()+rJ3.getHeight()-42,0);

        assertEquals(pixelN4, pixelJ4,0);
    }
}
 
Example 9
Source File: TestNDPINativeAndJava.java    From orbit-image-analysis with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Here we check that the NDPI Reader that uses Native libraries produces the
 * same results as the Java version (which uses Bioformats), using Fluorescence
 * image as a test.
 * @throws Exception :-(
 */
@Test
public void testReaderIdenticalFluorescenceTilePixels() throws Exception {
        OrbitTiledImage2 imgJava = getRecognitionFrameJava(TestImageType.FLUORESCENCE, 0).bimg.getImage();
        OrbitTiledImage2 imgNative = getRecognitionFrameNative(TestImageType.FLUORESCENCE, 0).bimg.getImage();

        // The images should have the same dimension irrespective of the reader used.
        assertEquals(imgJava.getWidth(), imgNative.getWidth());
        assertEquals(imgJava.getHeight(), imgNative.getHeight());

        // rJ has tile size of 512, and rN has tile size of 1024 - which is why tile coordinates are different in each case.
        WritableRaster rJ = (WritableRaster) imgJava.getTile(0, 0).createTranslatedChild(0, 0);
        WritableRaster rN = (WritableRaster) imgNative.getTile(0, 0).createTranslatedChild(0, 0);

        int pixelJ = rJ.getSample(rJ.getMinX() + rJ.getWidth() - 100, rJ.getMinY() + rJ.getHeight() - 100, 0);
        int pixelN = rN.getSample(rN.getMinX() + rN.getWidth() - 100, rN.getMinY() + rN.getHeight() - 100, 0);

        // 'Random' pixel values at the first tile should have the same value.
        assertEquals(pixelJ, pixelN, 1);

        // rJ has tile size of 512, and rN has tile size of 1024 - which is why tile coordinates are different in each case.
        WritableRaster rJ2 = (WritableRaster) imgJava.getTile(3, 4).createTranslatedChild(0, 0);
        WritableRaster rN2 = (WritableRaster) imgNative.getTile(7, 9).createTranslatedChild(0, 0);

        // A test that shouldn't suffer from: https://github.com/ome/bioformats/issues/3059
        int pixelJ2 = rJ2.getSample(rJ.getMinX() + rJ.getWidth() - 100, rJ.getMinY() + rJ.getHeight() - 8, 0);
        int pixelN2 = rN2.getSample(rN.getMinX() + rN.getWidth() - 100, rN.getMinY() + rN.getHeight() - 8, 0);

        // Pixels at the same place on the last tile should have the same value.
        assertEquals(pixelJ2, pixelN2, 2);

        // A test that should suffer from: https://github.com/ome/bioformats/issues/3059
        int pixelJ2a = rJ2.getSample(rJ.getMinX() + rJ.getWidth() - 100, rJ.getMinY() + rJ.getHeight()-1, 0);
        int pixelN2a = rN2.getSample(rN.getMinX() + rN.getWidth() - 100, rN.getMinY() + rN.getHeight()-1, 0);

        // Pixels at the same place on the last tile should have the same value.
        assertEquals(pixelJ2a, pixelN2a, 2);

        // Extract an area from the image (to avoid tile size differences)
        Rectangle rect = new Rectangle(imgJava.getWidth()-456,imgJava.getHeight()-456,1024,1024);
        WritableRaster rJ3 = (WritableRaster) imgJava.getData(rect).createTranslatedChild(0,0);
        WritableRaster rN3 = (WritableRaster) imgNative.getData(rect).createTranslatedChild(0,0);

        // Grab the first pixel
        int pixelJ3 = rJ3.getSample(0,0,0);
        int pixelN3 = rN3.getSample(0,0,0);

        assertEquals(pixelN3, pixelJ3,6);

        // Grab a more random pixel
        int pixelN4 = rN3.getSample(rN3.getMinX()+rN3.getWidth()-666, rN3.getMinY()+rN3.getHeight()-42,0);
        int pixelJ4 = rJ3.getSample(rJ3.getMinX()+rJ3.getWidth()-666, rJ3.getMinY()+rJ3.getHeight()-42,0);

        assertEquals(pixelN4, pixelJ4,2);
}
 
Example 10
Source File: OracleText.java    From magarena with GNU General Public License v3.0 4 votes vote down vote up
private static BufferedImage trimTransparency(BufferedImage image) {
    WritableRaster raster = image.getAlphaRaster();
    int width = raster.getWidth();
    int height = raster.getHeight();
    int left = 0;
    int top = 0;
    int right = width - 1;
    int bottom = height - 1;
    int minRight = width - 1;
    int minBottom = height - 1;

    top:
    for (;top < bottom; top++){
        for (int x = 0; x < width; x++){
            if (raster.getSample(x, top, 0) != 0){
                minRight = x;
                minBottom = top;
                break top;
            }
        }
    }

    left:
    for (;left < minRight; left++){
        for (int y = height - 1; y > top; y--){
            if (raster.getSample(left, y, 0) != 0){
                minBottom = y;
                break left;
            }
        }
    }

    bottom:
    for (;bottom > minBottom; bottom--){
        for (int x = width - 1; x >= left; x--){
            if (raster.getSample(x, bottom, 0) != 0){
                minRight = x;
                break bottom;
            }
        }
    }

    right:
    for (;right > minRight; right--){
        for (int y = bottom; y >= top; y--){
            if (raster.getSample(right, y, 0) != 0){
                break right;
            }
        }
    }

    return image.getSubimage(left, top, right - left + 1, bottom - top + 1);
}
 
Example 11
Source File: ImageTrimUtil.java    From Pixelitor with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Returns image bounding box trimmed from transparent pixels (alpha channel = 0)
 */
public static Rectangle getTrimRect(BufferedImage image) {
    WritableRaster raster = image.getAlphaRaster();
    int width = raster.getWidth();
    int height = raster.getHeight();
    int left = 0;
    int top = 0;
    int right = width - 1;
    int bottom = height - 1;
    int minRight = width - 1;
    int minBottom = height - 1;

    top:
    for (; top < bottom; top++) {
        for (int x = 0; x < width; x++) {
            if (raster.getSample(x, top, 0) != 0) {
                minRight = x;
                minBottom = top;
                break top;
            }
        }
    }

    left:
    for (; left < minRight; left++) {
        for (int y = height - 1; y > top; y--) {
            if (raster.getSample(left, y, 0) != 0) {
                minBottom = y;
                break left;
            }
        }
    }

    bottom:
    for (; bottom > minBottom; bottom--) {
        for (int x = width - 1; x >= left; x--) {
            if (raster.getSample(x, bottom, 0) != 0) {
                minRight = x;
                break bottom;
            }
        }
    }

    right:
    for (; right > minRight; right--) {
        for (int y = bottom; y >= top; y--) {
            if (raster.getSample(right, y, 0) != 0) {
                break right;
            }
        }
    }

    return new Rectangle(left, top, right - left + 1, bottom - top + 1);
}
 
Example 12
Source File: ImportHeightMapDialog.java    From WorldPainter with GNU General Public License v3.0 4 votes vote down vote up
private void loadImage() {
        try {
            image = null; // Set image to null first to make more memory available for loading the new image
            image = ImageIO.read(selectedFile);
            if (image == null) {
                labelImageDimensions.setForeground(Color.RED);
                labelImageDimensions.setText("Not an image file, or damaged file!");
                selectedFile = null;
            } else if ((image.getType() == BufferedImage.TYPE_BYTE_BINARY) || (image.getType() == BufferedImage.TYPE_BYTE_INDEXED)) {
                labelImageDimensions.setForeground(Color.RED);
                labelImageDimensions.setText("Indexed image not supported! Please convert to non-indexed.");
                selectedFile = null;
            } else if (image.isAlphaPremultiplied()) {
                labelImageDimensions.setForeground(Color.RED);
                labelImageDimensions.setText("Premultiplied alpha not supported! Please convert to non-premultiplied.");
                selectedFile = null;
            } else {
                if (image.getType() == BufferedImage.TYPE_CUSTOM) {
                    spinnerScale.setValue(100);
                    spinnerScale.setEnabled(false);
                    spinnerScale.setToolTipText("<html>Scaling not supported for grey scale images with an alpha channel!<br>To enable scaling, please remove the alpha channel.</html>");
                } else {
                    spinnerScale.setEnabled(true);
                    spinnerScale.setToolTipText(null);
                }
                labelImageDimensions.setForeground(null);
                int width = image.getWidth(), height = image.getHeight();
                bitDepth = image.getSampleModel().getSampleSize(0);
                WritableRaster raster = image.getRaster();
                int imageLowValue = Integer.MAX_VALUE;
                imageHighValue = Integer.MIN_VALUE;
                int imageMaxHeight = (int) Math.pow(2, bitDepth) - 1;
                boolean invert = checkBoxInvert.isSelected();
outer:          for (int x = 0; x < width; x++) {
                    for (int y = 0; y < height; y++) {
                        int value = invert ? (imageMaxHeight - raster.getSample(x, y, 0)) : raster.getSample(x, y, 0);
                        if (value < imageLowValue) {
                            imageLowValue = value;
                        }
                        if (value > imageHighValue) {
                            imageHighValue = value;
                        }
                        if ((imageLowValue == 0) && (imageHighValue == imageMaxHeight)) {
                            // No point in looking any further!
                            break outer;
                        }
                    }
                }
                setMaximum(spinnerImageLow, imageMaxHeight);
                setMaximum(spinnerImageHigh, imageMaxHeight);

                // Set levels to reasonable defaults
                selectDefaultVerticalScaling();

                labelImageDimensions.setText(String.format("Image size: %d x %d, %d bits, lowest value: %d, highest value: %d", width, height, bitDepth, imageLowValue, imageHighValue));
                updateWorldDimensions();
                updatePreview();
            }
        } catch (IOException e) {
            logger.error("I/O error loading image " + selectedFile, e);
            labelImageDimensions.setForeground(Color.RED);
            labelImageDimensions.setText(String.format("I/O error loading image (message: %s)!", e.getMessage()));
            selectedFile = null;
        }
    }