简体   繁体   English

来自java BufferedImage的奇怪RGB值getRGB()

[英]Weird RGB value from java BufferedImage getRGB()

Im trying to get RGB value from a grayscale image and it was return wrong(?) RGB value. 我试图从灰度图像中获取RGB值,并返回错误的(?)RGB值。 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 在颜色选择器使用时,第一个像素RGB值R:153,G:153,B:153但我的代码打印

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? 而且,我试图使用MATLAB灰度值的精确像素也是153.我这样做错了吗?

this is the image 这是图像

在此输入图像描述

This is because image.getRGB(x, y) by definition returns ARGB values in sRGB colorspace . 这是因为image.getRGB(x, y)按定义返回sRGB颜色空间中的 ARGB值。

From the JavaDoc : 来自JavaDoc

Returns an integer pixel in the default RGB color model ( TYPE_INT_ARGB ) and default sRGB colorspace. 返回默认RGB颜色模型( TYPE_INT_ARGB )和默认sRGB颜色空间中的整数像素。 Color conversion takes place if this default model does not match the image ColorModel . 如果此默认模型与图像ColorModel不匹配,则会进行颜色转换。

Matlab and other tools likely use a linear RGB or gray color space, and this is why the values are different. Matlab和其他工具可能使用线性RGB或灰色空间,这就是值不同的原因。

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. 如果图像是灰度( TYPE_BYTE_GRAY ),则可以通过访问Raster及其getDataElements方法从Java获取相同的值。

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. 如果图像是TYPE_BYTE_GRAY ,则pixel将是具有单个元素的byte数组。

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

This value will be 153 in your case. 在您的情况下,此值将为153

Just try this 试试吧

System.out.println(image.getRaster().getSample(0, 0, 0));  //R
System.out.println(image.getRaster().getSample(0, 0, 1));  //G
System.out.println(image.getRaster().getSample(0, 0, 2));  //B

Here 这里

getSample(int x, int y, int b)
Returns the sample in a specified band for the pixel located at (x,y) as an int. 将位于(x,y)的像素的指定band中的样本返回为int。 [According to this] [根据这个]

Parameters: 参数:
x - The X coordinate of the pixel location x - 像素位置的X坐标
y - The Y coordinate of the pixel location y - 像素位置的Y坐标
b - The band to return b - 返回的乐队
b = [0,1,2] for [R,G,B] [R,G,B]的b = [0,1,2]

and also take a look at BufferedImage getRGB vs Raster getSample 并且还看一下BufferedImage getRGB vs Raster getSample

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM