【问题标题】:Getting Greyscale pixel value from RGB colourspace in Java using BufferedImage使用 BufferedImage 从 Java 中的 RGB 颜色空间获取灰度像素值
【发布时间】:2010-03-23 11:47:10
【问题描述】:

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

我打算通过使用它来简单地平均 RGB 值;

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

然后平均红、绿、蓝。

但我觉得对于这样一个简单的操作,我一定错过了一些东西......

在对另一个问题做出很好的回答之后,我应该弄清楚我想要什么。

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

这可以通过平均等来完成,但我正在寻找一种 OTS 实现来节省我的几行代码。

【问题讨论】:

    标签: java image-processing bufferedimage


    【解决方案1】:

    tutorial 显示了 3 种方法:

    通过更改ColorSpace

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

    通过绘制到灰度BufferedImage

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

    通过使用GrayFilter

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

    【讨论】:

    • 感谢@polygenelubricants,但我实际上只是在寻找单个像素的等效灰度值(但已将链接教程添加为书签:))
    【解决方案2】:

    这并不像听起来那么简单,因为is no 100% correct answer for how to map a colour to greyscale.

    我使用的方法是将 RGB 转换为 HSL,然后将 S 部分设为 0(并可选择转换回 RGB),但这可能不是您想要的。 (它相当于最高和最低 rgb 值的平均值,因此与所有 3 的平均值略有不同)

    【讨论】:

    • 谢谢,我最终选择了与您的答案相关的 HSV
    【解决方案3】:

    平均听起来不错,尽管 Matlab rgb2gray 使用加权和。

    查看Matlab rgb2gray

    更新
    我尝试在 Java 中实现 Matlab 方法,也许我做错了,但平均得到了更好的结果。

    【讨论】:

      猜你喜欢
      • 2021-08-05
      • 2013-04-05
      • 1970-01-01
      • 1970-01-01
      • 2015-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多