简体   繁体   中英

Grayscale image filter

I'm working on an image filter for grayscaling with a matrix and dividing the R+G+B colors by 3 in the follow loop as you see below.

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

But I've heard that doing it with intensity would be a lot better, so I tried something like this but it doesn't seem to work. My GUI application freezes when I'm trying to filter it like this. Perhaps anyone could help me out with this loop?

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

If required I can post the other classes I'm working with but I don't think it's necessary since the code is pretty much self-explanatory.

Edit: Here comes the intensity method:

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

Thanks, Michael.

As said in the comments above, you may use a better equation to compute the grayscale : 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); 

The computeIntensity is already computing the grayscales, so no need to re-iterate over all the pixels. You may even rename it to computeGrayScales

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM