我正在研究一个带有矩阵的灰度图像过滤器,并在下面的循环中将 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;
}
谢谢迈克尔。
如上面的评论中所述,您可以使用更好的方程来计算灰度: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