我必须对缓冲图像进行n轮行像素排序,循环每行并将当前像素的亮度与当前像素左边的亮度进行比较。如果电流的亮度小于左边的亮度,我需要交换像素的颜色。这是我目前的代码。
public static int getRed(int rgb) { return (rgb >> 16) & 0xff; }
public static int getGreen(int rgb) { return (rgb >> 8) & 0xff; }
public static int getBlue(int rgb) { return rgb & 0xff; }
public static int rgbColour(int r, int g, int b) {
return (r << 16) | (g << 8) | b;
}
public static double brightness(int rgb) {
int r = getRed(rgb);
int g = getGreen(rgb);
int b = getBlue(rgb);
return 0.21*r + 0.72*g + 0.07*b;
}
public static BufferedImage convertToGrayscale(BufferedImage img) {
BufferedImage result = new BufferedImage(
img.getWidth(), img.getHeight(), BufferedImage.TYPE_INT_RGB
);
for(int x = 0; x < img.getWidth(); x++) {
for(int y = 0; y < img.getHeight(); y++) {
int col = img.getRGB(x, y);
int gr = (int)brightness(col);
result.setRGB(x, y, rgbColour(gr, gr, gr));
}
}
return result;
}
我给出的方法如下。
{{1}}
答案 0 :(得分:0)
比较后您没有正确切换值:
for(int x =1; x<img.getWidth();x++){
int temp = img.getRGB(x-1,y);
int temp2 = img.getRGB(x, y);
...
if (gr2 < gr) {
result.setRGB(x, y, rgbColour(temp2,temp2,temp2)); // same as in img
result.setRGB(x-1, y, rgbColour(temp,temp,temp)); // same as in img
}
}
请尝试使用if-clause:
...
if (gr2 < gr) { // swap values in result
result.setRGB(x-1, y, rgbColour(temp2,temp2,temp2));
result.setRGB(x, y, rgbColour(temp,temp,temp));
} else { // keep values in result same as in img
result.setRGB(x, y, rgbColour(temp2,temp2,temp2));
result.setRGB(x-1, y, rgbColour(temp,temp,temp));
}