【发布时间】: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