我想使用java.awt.image.BufferedImage为灰度转换做一个简单的颜色.我是图像处理领域的初学者,所以如果我感到困惑,请原谅.
我的输入图像是一个RGB 24位图像(没有alpha),我想在输出上获得一个8位灰度级BufferedImage,这意味着我有一个这样的类(为清晰起见省略了详细信息):
public class GrayscaleFilter {
private BufferedImage colorFrame;
private BufferedImage grayFrame =
new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY);
到目前为止,我已经成功尝试了2种转换方法,首先是:
private BufferedImageOp grayscaleConv =
new ColorConvertOp(ColorSpace.getInstance(ColorSpace.CS_GRAY), null);
protected void filter() {
grayscaleConv.filter(colorFrame, grayFrame);
}
第二个是:
protected void filter() {
WritableRaster raster = grayFrame.getRaster();
for(int x = 0; x < raster.getWidth(); x++) {
for(int y = 0; y < raster.getHeight(); y++){
int argb = colorFrame.getRGB(x,y);
int r = (argb >> 16) & 0xff;
int g = (argb >> 8) & 0xff;
int b = (argb ) & 0xff;
int l = (int) (.299 * r + .587 * g + .114 * b);
raster.setSample(x, y, 0, l);
}
}
}
第一种方法工作得更快,但产生的图像非常暗,这意味着我失去了带宽,这是不可接受的(在灰度和sRGB ColorModel之间使用一些颜色转换映射称为tosRGB8LUT,这对我来说效果不佳,到目前为止正如我所知,但我不确定,我只是假设使用了这些值.第二种方法效果较慢,但效果非常好.
有没有一种方法可以将这两者结合起来,例如:使用自定义索引ColorSpace for ColorConvertOp?如果有,你能举个例子吗?
提前致谢.