实现Matlab';Java中的rgb2gray

实现Matlab';Java中的rgb2gray,java,matlab,image-processing,rgb,grayscale,Java,Matlab,Image Processing,Rgb,Grayscale,我正试图用Java实现Matlab的rgb2gray。我有以下代码: public BufferedImage convert(BufferedImage bi){ int heightLimit = bi.getHeight(); int widthLimit = bi.getWidth(); BufferedImage converted = new BufferedImage(widthLimit, heightLimit, BufferedImag

我正试图用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;
}
公共BuffereImage转换(BuffereImage bi){
int heightLimit=bi.getHeight();
int widthLimit=bi.getWidth();
BuffereImage converted=新的BuffereImage(宽度限制、高度限制、,
BuffereImage.TYPE_BYTE_GRAY);
对于(int height=0;height
现在,我确实得到了一个灰度图像,但与我从Matlab得到的图像相比,它太暗了。另外,将图像转换为灰度的最简单方法是使用类型为_BYTE_GRAY的BuffereImage,然后只复制类型为_INT_u(a)RGB的BuffereImage的像素。但即使这种方法给出的图像比Matlab的要暗,尽管灰度足够合适。我还研究了如何使用
重新缩放
。但是,我没有在“重缩放”中找到设置每像素灰度的方法

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

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

指定类型转换高于乘法。您正在将浮点常量强制转换为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,这是一个众所周知的公式,到处都有引用,例如。有一个答案被删除了,其中包括一个不太正确的样本计算,但是如果你替换了适当的常数,它是完全正确的。