我想使用java.awt.image.BufferedImage
. 我是图像处理领域的初学者,所以如果我感到困惑,请原谅。
我的输入图像是 RGB 24 位图像(无 alpha),我想BufferedImage
在输出上获得 8 位灰度,这意味着我有一个这样的类(为清楚起见省略了细节):
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
为ColorConvertOp
? 如果是的话,你能给我举个例子吗?
提前致谢。