Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weird RGB value from java BufferedImage getRGB()

Im trying to get RGB value from a grayscale image and it was return wrong(?) RGB value. Here is the code.

Color color = new Color(image.getRGB(0, 0));
System.out.print(color.getRed());
System.out.print(color.getGreen());
System.out.print(color.getBlue());

At a color picker was using, the first pixel RGB value R:153,G:153,B:153 but my code print

203203203

Why this thing happened? And also, im trying to use MATLAB Grayscale values for the exact pixel is also 153. Am i doing this wrong?

this is the image

enter image description here

like image 750
Ikhwan Nizwar A Avatar asked Jan 08 '23 11:01

Ikhwan Nizwar A


1 Answers

This is because image.getRGB(x, y) by definition returns ARGB values in sRGB colorspace.

From the JavaDoc:

Returns an integer pixel in the default RGB color model (TYPE_INT_ARGB) and default sRGB colorspace. Color conversion takes place if this default model does not match the image ColorModel.

Matlab and other tools likely use a linear RGB or gray color space, and this is why the values are different.

You can get the same values from Java if the image is gray scale (TYPE_BYTE_GRAY), by accessing the Raster and its getDataElements method.

Object pixel = raster.getDataElements(0, 0, null); // x, y, data array (initialized if null)

If the image is TYPE_BYTE_GRAY, pixel will be a byte array with a single element.

int grayValue = ((byte[]) pixel)[0] & 0xff;

This value will be 153 in your case.

like image 147
Harald K Avatar answered Jan 17 '23 20:01

Harald K