我正在尝试创建一个程序,在我的计算机科学课上选择的图像上应用灰度滤镜。我在教程中找到了以下代码,它演示了灰度算法,其中图像中每个像素的 R、G 和 B 值被替换为 RGB 值的平均值。
import java.io.File;
import java.io.IOException;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
public class Grayscale{
public static void main(String args[])throws IOException{
BufferedImage img = null;
File f = null;
//read image
try{
f = new File("D:\\Image\\Taj.jpg");
img = ImageIO.read(f);
}catch(IOException e){
System.out.println(e);
}
//get image width and height
int width = img.getWidth();
int height = img.getHeight();
//convert to grayscale
for(int y = 0; y < height; y++){
for(int x = 0; x < width; x++){
int p = img.getRGB(x,y);
int a = (p>>24)&0xff;
int r = (p>>16)&0xff;
int g = (p>>8)&0xff;
int b = p&0xff;
//calculate average
int avg = (r+g+b)/3;
//replace RGB value with avg
p = (a<<24) | (avg<<16) | (avg<<8) | avg;
img.setRGB(x, y, p);
}
}
//write image
try{
f = new File("D:\\Image\\Output.jpg");
ImageIO.write(img, "jpg", f);
}catch(IOException e){
System.out.println(e);
}
}//main() ends here
}//class ends here
问题是,该程序没有在某些图像上正确应用灰度滤镜。例如,代码可以在此图像上正确应用过滤器,创建灰度图像。但是下面的 彩虹图像看起来像这样,应用了灰度滤镜。
为什么过滤器上方会显示红色、绿色、蓝色和粉红色?我的理解是,当一个像素的R、G、B值相同时,应该创建一个灰色?