使用Java中的数组矩阵将图像转换为灰度图像

3
我正在创建一个图像过滤程序,我想使用数组矩阵将彩色图片转换为灰度图片。
以下是我目前的代码:
import java.awt.Color;
import se.lth.cs.ptdc.images.ImageFilter;

public class GrayScaleFilter extends ImageFilter {

    public GrayScaleFilter(String name){
        super(name);
    }

    public Color[][] apply(Color[][] inPixels, double paramValue){
        int height = inPixels.length;
        int width = inPixels[0].length;
        Color[][] outPixels = new Color[height][width];
        for (int i = 0; i < 256; i++) {
          grayLevels[i] = new Color(i, i, i);
        }

        for(int i = 0; i < height; i++){
            for(int j = 0; j < width; j++){
                Color pixel = inPixels[i][j];
            outPixels[i][j] = grayLevels[index];                    
            }
        }
        return outPixels;
    }
}

看起来我应该使用这个公式:((R+G+B)/3)
我想创建一个像这样的数组矩阵:
 Color[] grayLevels = new Color[256];
    // creates the color (0,0,0) and puts it in grayLevels[0],
    // (1,1,1) in grayLevels[1], ..., (255,255,255) in grayLevels[255]

这是我想要使用灰度时所指的类:
public abstract Color[][] apply(Color[][] inPixels, double paramValue);

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;
}

如何实现这一点的任何反馈?而不是使用 outPixels[i][j] = new Color(intensity, intensity, intensity);
1个回答

3

按照以下方式构建grayLevels数组:

for (int i = 0; i < 256; i++) {
  grayLevels[i] = new Color(i, i, i);
}

然后,当您需要某种颜色时,只需将其作为grayLevels[index]检索即可。

应该是 outPixels = grayLevels[index]。我猜目标是不要创建太多的Color对象。 - Dan D.
您是否还需要能够构建BufferedImage并将其保存到磁盘的代码? - Dan D.
我按照你说的进行了设置,但是出现了“index无法解析为变量”的错误。我已经有一个完成的GUI来构建图像。 - Rob
索引是这个值:(short) ((c.getRed() + c.getGreen() + c.getBlue()) / 3) - Dan D.
让我们在聊天中继续这个讨论:http://chat.stackoverflow.com/rooms/19904/discussion-between-rob-and-dan - Rob
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接