简体   繁体   English

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

[英]Getting Greyscale pixel value from RGB colourspace in Java using BufferedImage

Anyone know of a simple way of converting the RGBint value returned from <BufferedImage> getRGB(i,j) into a greyscale value? 有人知道将从<BufferedImage> getRGB(i,j)返回的RGBint值转换为灰度值的简单方法吗?

I was going to simply average the RGB values by breaking them up using this; 我只是通过使用它来分解它们来简单地平均RGB值;

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

and then average red,green,blue. 然后平均红色,绿色,蓝色。

But i feel like for such a simple operation I must be missing something... 但我觉得这样一个简单的操作我必须遗漏一些东西......

After a great answer to a different question, I should clear up what i want. 在对一个不同的问题做出了很好的回答后,我应该清楚自己想要什么。

I want to take the RGB value returned from getRGB(i,j), and turn that into a white-value in the range 0-255 representing the "Darkness" of that pixel. 我想从getRGB(i,j)返回RGB值,并将其转换为0-255范围内的白色值,表示该像素的“暗度”。

This can be accomplished by averaging and such but I am looking for an OTS implementation to save me a few lines. 这可以通过平均等来实现,但我正在寻找一个OTS实现来节省几行。

This tutorial shows 3 ways to do it: 教程介绍了3种方法:

By changing ColorSpace 通过改变ColorSpace

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

By drawing to a grayscale BufferedImage 通过绘制到灰度BufferedImage

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

By using GrayFilter 通过使用GrayFilter

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

this isn't as simple as it sounds because there is no 100% correct answer for how to map a colour to greyscale. 这并不像听起来那么简单,因为对于如何将颜色映射到灰度,没有100%正确的答案。

the method i'd use is to convert RGB to HSL then 0 the S portion (and optionally convert back to RGB) but this might not be exactly what you want. 我使用的方法是将RGB转换为HSL然后转换为S部分(并且可选地转换回RGB),但这可能不是您想要的。 (it is equivalent to the average of the highest and lowest rgb value so a little different to the average of all 3) (它相当于最高和最低rgb值的平均值,因此与所有3的平均值略有不同)

Averaging sounds good, although Matlab rgb2gray uses weighted sum. 虽然Matlab rgb2gray使用加权和,但平均听起来不错。

Check Matlab rgb2gray 检查Matlab rgb2gray

UPDATE UPDATE
I tried implementing Matlab method in Java, maybe i did it wrong, but the averaging gave better results. 我尝试在Java中实现Matlab方法,也许我做错了,但平均值给出了更好的结果。

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

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