Search code examples
javamatrixsumbufferedimageraster

Is there a function to sum the rasters of two buffered images?


I'm doing 2D filteing and want to do element by element addition on grayscale BufferedImages. Is there an existing function that will complete this for me or do i need to make one from scrach?

Is there some sort of matrix class that converts a raster to a matrix to simplyfy this problem?

Edit: here is the general gist of it

    BufferedImageOp opX = new ConvolveOp(new Kernel(3,3, kernelX));
    BufferedImageOp opY = new ConvolveOp(new Kernel(3,3, kernelY));
    BufferedImage filtImageX = opX.filter(sourceImage, null);
    BufferedImage filtImageY = opY.filter(sourceImage, null);
    BufferedImage outputImage = addBufferedImages(filtImageX, filtImageY);

Grayscale Conversion:

public void toGrayscale() { 
     BufferedImageOp op = new ColorConvertOp(ColorSpace.getInstance(ColorSpace.CS_GRAY), null); 
     sourceImage = op.filter(sourceImage, null); 
}

Solution

  • I am not familiar with any java libs that do that for you.

    You can get pixel at [i,j] with: image.getRGB(i, j);

    BufferedImage image = ...;
    BufferedImage resultImage = ...
    
    int rgb= image.getRGB(i, j);
    resultImage.setRGB(i, j, rgb);
    

    You can also convert a buffered image to a byte array [ https://stackoverflow.com/a/7388025/1007845 ].
    See this thread: how to convert image to byte array in java? to get a WritableRaster

    EDIT:

    It seems that WritableRaster might be useful in this case: http://docs.oracle.com/javase/1.4.2/docs/api/java/awt/image/WritableRaster.html

    WritableRaster raster = image.getRaster();
    
    for(int h=0;h<height;h++) {
        for(int w=0;w<width;w++) {
            int colour = 127;
          raster.setSample(w,h,0,colour); 
       }
    }