【问题标题】:Implementing Matlab's rgb2gray in Java在 Java 中实现 Matlab 的 rgb2gray
【发布时间】:2012-03-16 15:13:31
【问题描述】:

我正在尝试根据 http://www.mathworks.com/help/toolbox/images/ref/rgb2gray.html 在 Java 中实现 Matlab 的 rgb2gray 。我有以下代码:

public BufferedImage convert(BufferedImage bi){
    int heightLimit = bi.getHeight();
    int widthLimit = bi.getWidth();
    BufferedImage converted = new BufferedImage(widthLimit, heightLimit,
        BufferedImage.TYPE_BYTE_GRAY);

    for(int height = 0; height < heightLimit; height++){
        for(int width = 0; width < widthLimit; width++){
            // Remove the alpha component
            Color c = new Color(bi.getRGB(width, height) & 0x00ffffff);
            // Normalize
            int newRed = (int) 0.2989f * c.getRed();
            int newGreen = (int) 0.5870f * c.getGreen();
            int newBlue = (int) 0.1140f * c.getBlue();
            int roOffset = newRed + newGreen + newBlue;
            converted.setRGB(width, height, roOffset);
        }
    }

    return converted;
}

现在,我确实获得了灰度图像,但与从 Matlab 获得的图像相比,它太暗了。 AFAIK,将图像转换为灰度的最简单方法是使用 TYPE_BYTE_GRAY 类型的 BufferedImage,然后复制 TYPE_INT_(A)RGB 的 BufferedImage 的像素。但即使是这种方法也给出了一个比 Matlab 更暗的图像,尽管灰度足够好。我也研究过使用RescaleOp。但是,我无论如何都找不到 RescaleOp 来设置每像素的灰度。

作为附加测试,我打印出由 Java 和 Matlab 生成的图像矩阵。在 Java 中,我得到类似 6316128 6250335 6118749 6118749 6250335 6447714 的数字,而在 Matlab 中,我只得到类似 116 117 119 120 119 115 的数字(两个矩阵的前六个数字)。

如何获得类似于 Matlab 的输出?

【问题讨论】:

    标签: java matlab image-processing rgb grayscale


    【解决方案1】:

    operator precedence in Java 指定类型转换高于乘法。您将浮点常量转换为 0,所以我根本不明白您是如何获得灰度结果的。易于修复:

            int newRed = (int) (0.2989f * c.getRed());
            int newGreen = (int) (0.5870f * c.getGreen());
            int newBlue = (int) (0.1140f * c.getBlue());
    

    我还将0.2989 替换为0.2990,因为它似乎是文档中的错字。

    【讨论】:

    • 嗨,谢谢。这似乎解决了我的灰度问题(通过仔细检查来证明/反驳)。但我想知道您从哪里得到对 Matlab 文档的更正?我似乎无法在其他地方找到它。
    • @skytreader,这是一个众所周知的公式,参考无处不在,例如en.wikipedia.org/wiki/… 。有一个答案被删除,其中包含一个不太正确的示例计算,但如果您替换了适当的常数,则完全正确。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-28
    • 1970-01-01
    • 2014-04-12
    相关资源
    最近更新 更多