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.The
computeIntensityis already computing the grayscales, so no need to re-iterate over all the pixels. You may even rename it tocomputeGrayScales