代码之家  ›  专栏  ›  技术社区  ›  Bolster

用缓冲区模式从Java中的RGB颜色空间获取灰度像素值

  •  4
  • Bolster  · 技术社区  · 16 年前

    任何人都知道转换从 <BufferedImage> getRGB(i,j) 变成灰度值?

    我只是简单的平均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实现来节省我的几行代码。

    3 回复  |  直到 16 年前
        1
  •  3
  •   jk.    16 年前

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

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

        2
  •  8
  •   polygenelubricants    16 年前

    这个 tutorial 显示了三种方法:

    通过改变 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);
    
        3
  •  0
  •   mohdajami    16 年前

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

    检查 Matlab rgb2gray

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