灰度图像滤镜

时间:2012-11-23 08:43:51

标签: java image matrix rgb bufferedimage

我正在制作一个图像滤镜,用于使用矩阵进行灰度校正,并在跟随循环中将R + G + B颜色除以3,如下所示。

for (int i = 0; i < height; i++) {
        for (int j = 0; j < width; j++) {
            Color c = inPixels[i][j];
            outPixels[i][j] = grayLevels[(c.getRed() + c.getGreen() + c.getBlue()) / 3];
        }
    }

但是我听说用强度做这件事会好很多,所以我试过这样的东西,但似乎没有用。当我试图像这样过滤它时,我的GUI应用程序冻结了。也许有人可以帮我解决这个问题吗?

 for (int i = 0; i < height; i++) { 
            for (int j = 0; j < width; j++) { 
                short[][] intensity = computeIntensity(inPixels); 
                Color c = inPixels[i][j]; 

                outPixels[i][j] = grayLevels[(c.getRed() + c.getGreen() + c.getBlue()) / 3];
        }

如果需要,我可以发布我正在使用的其他课程,但我不认为这是必要的,因为代码几乎是不言自明的。

编辑: 这是强度方法:

protected short[][] computeIntensity(Color[][] pixels) {
    int height = pixels.length;
    int width = pixels[0].length;
    short[][] intensity = new short[height][width];
    for (int i = 0; i < height; i++) {
        for (int j = 0; j < width; j++) {
            Color c = pixels[i][j];
            intensity[i][j] = (short) ((c.getRed() + c.getGreen() + c
                    .getBlue()) / 3);
        }
    }
    return intensity;
}

谢谢, 迈克尔。

1 个答案:

答案 0 :(得分:3)

正如上面的评论中所述,您可以使用更好的等式来计算灰度:red * 0.299 + green * 0.587 + blue * 0.114

protected Color[][] computeIntensity(Color[][] pixels) {
    int height = pixels.length;
    int width = pixels[0].length;
    Color[][] intensity = new Color[height][width];
    for (int i = 0; i < height; i++) {
        for (int j = 0; j < width; j++) {
            Color c = pixels[i][j];
            intensity[i][j] = new Color(c.getRed() * 0.299, c.getGreen() * 0.587, c.getBlue() * 0.114);
        }
    }
    return intensity;
}

outPixels = computeIntensity(inPixels); 

computeIntensity已经在计算灰度,因此无需重新遍历所有像素。您甚至可以将其重命名为computeGrayScales