我正在尝试实现Matlab的rgb2gray
在Java中根据http://www.mathworks.com/help/toolbox/images/ref/rgb2gray.html http://www.mathworks.com/help/toolbox/images/ref/rgb2gray.html。我有以下代码:
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 的输出?
The Java中的运算符优先级 https://stackoverflow.com/questions/2137690/java-operator-precedence-guidelines指定类型转换高于乘法。您将浮点常量转换为 0,所以我根本不明白您是如何获得灰度结果的。易于修复:
int newRed = (int) (0.2989f * c.getRed());
int newGreen = (int) (0.5870f * c.getGreen());
int newBlue = (int) (0.1140f * c.getBlue());
我也想替换0.2989
with 0.2990
因为它似乎是文档中的拼写错误。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)