Getting grayscale pixel values ​​from RGB colorspace in Java using BufferedImage

Does anyone know a simple way to convert the RGBint value returned from <BufferedImage> getRGB(i,j) to a grayscale value?

I was going to just average the RGB values, splitting them using this:

 int alpha = (pixel >> 24) & 0xff; int red = (pixel >> 16) & 0xff; int green = (pixel >> 8) & 0xff; int blue = (pixel) & 0xff; 

and then medium red, green, blue.

But I feel that something is missing for such a simple operation ...

After an excellent answer to another question, I have to clarify what I want.

I want to take the RGB value returned from getRGB (i, j) and turn it into a white value in the range 0-255, representing the "Darkness" of this pixel.

This can be achieved by averaging, etc., but I am looking for an OTS implementation to save multiple lines.

+4
source share
3 answers

it is not as simple as it seems, because it does not correspond to the 100% correct answer, how to compare color with shades of gray.

the method I would use is to convert RGB to HSL, then 0 part S (and maybe convert back to RGB), but that may not be exactly what you want. (this is equivalent to the average of the highest and lowest rgb, so it is slightly different from the average of all 3)

+3
source

This tutorial shows 3 ways to do this:

Changing ColorSpace

 ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_GRAY); ColorConvertOp op = new ColorConvertOp(cs, null); BufferedImage image = op.filter(bufferedImage, null); 

Pulling to Grayscale BufferedImage

 BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY); Graphics g = image.getGraphics(); g.drawImage(colorImage, 0, 0, null); g.dispose(); 

Using GrayFilter

 ImageFilter filter = new GrayFilter(true, 50); ImageProducer producer = new FilteredImageSource(colorImage.getSource(), filter); Image image = this.createImage(producer); 
+8
source

Averaging sounds good, although Matlab rgb2gray uses a weighted sum.

Check Matlab rgb2gray

UPDATE
I tried to implement the Matlab method in Java, maybe I did it wrong, but averaging gave better results.

0
source

Source: https://habr.com/ru/post/1304860/


All Articles