使用BufferedImage从Java中获取RGB colourspace的灰度像素值

Bol*_*ter 4 java bufferedimage image-processing

有人知道将RGBint值<BufferedImage> getRGB(i,j)转换为灰度值的简单方法吗?

我只是通过使用它来分解它们来简单地平均RGB值;

int alpha = (pixel >> 24) & 0xff;
int red = (pixel >> 16) & 0xff;
int green = (pixel >> 8) & 0xff;
int blue = (pixel) & 0xff;
Run Code Online (Sandbox Code Playgroud)

然后平均红色,绿色,蓝色.

但我觉得这样一个简单的操作我必须遗漏一些东西......

在对一个不同的问题做出了很好的回答之后,我应该清楚自己想要什么.

我想从getRGB(i,j)返回RGB值,并将其转换为0-255范围内的白色值,表示该像素的"暗度".

这可以通过平均等来实现,但我正在寻找一个OTS实现来节省几行.

pol*_*nts 8

教程介绍了3种方法:

通过改变 ColorSpace

ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_GRAY);
ColorConvertOp op = new ColorConvertOp(cs, null);
BufferedImage image = op.filter(bufferedImage, null);
Run Code Online (Sandbox Code Playgroud)

通过绘制灰度 BufferedImage

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

通过使用 GrayFilter

ImageFilter filter = new GrayFilter(true, 50);
ImageProducer producer = new FilteredImageSource(colorImage.getSource(), filter);
Image image = this.createImage(producer);
Run Code Online (Sandbox Code Playgroud)