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 valu开发者_如何转开发e each pixel of the image....
Thanks for advance
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.
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.
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.
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.
}
}
精彩评论