Duke Irhamz
Duke Irhamz

Reputation: 23

How to get gray level each pixel of the image in java

there... I have some question about my homework on image processing using java. My question : how to get gray level value each pixel of the rgb image in java programming???

I just know a little about how to get rgb value each pixel by syntax image.getRGB(x,y) for return rgb value. I have no idea for to get gray level value each pixel of the image....

Thanks for advance

Upvotes: 2

Views: 4760

Answers (4)

Raist
Raist

Reputation: 99

Complementing Daniel's answer:

WritableRaster wr = myBufferedImage.getRaster();

for(int i = 0; i < myBufferedImage.getWidth(); i++){
    for(int j = 0; j < myBufferedImage.getHeight(); j++){
        int grayLevelPixel = wr.getSample(i, j, 0);
        wr.setSample(i, j, 0, grayLevelPixel); // Setting same gray level, will do nothing on the image, just to show how.
    }
}

Upvotes: 0

Daniel Devlin
Daniel Devlin

Reputation: 115

I agree with the previous answer. Create the BufferedImage like BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY). From what I understand a raster is for reading pixel data and a writable raster for writing pixel data or updating pixels. I always use writable raster although this may not be the best way to do it, because you can read pixel data and set pixel values. You can get the raster by WritableRaster raster = image.getRaster(); you can then get the value of a pixel by using raster.getSample(x, y, 0); The 0 in the arguments is for the band you want to get which for gray scale images should be 0.

Upvotes: 1

MeBigFatGuy
MeBigFatGuy

Reputation: 28588

You could also set up a BufferedImage of type TYPE_BYTE_GRAY, and draw the picture into it, then get the raster data and find the values.

Upvotes: 0

WhiteFang34
WhiteFang34

Reputation: 72049

First you'll need to extract the red, green and blue values from each pixel that you get from image.getRGB(x, y). See this answer about that. Then read about converting color to grayscale.

Upvotes: 1

Related Questions