0

我正在尝试创建一个程序,在我的计算机科学课上选择的图像上应用灰度滤镜。我在教程中找到了以下代码,它演示了灰度算法,其中图像中每个像素的 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值相同时,应该创建一个灰色?

4

1 回答 1

0

来自 JavaDocBufferedImage.setRGB()

“将此 BufferedImage 中的像素设置为指定的 RGB 值。假定该像素位于默认 RGB 颜色模型、TYPE_INT_ARGB 和默认 sRGB 颜色空间中。对于具有 IndexColorModel 的图像,选择颜色最接近的索引。”

为了解决这个问题,使用所需的颜色空间创建一个新的 BufferedImage,与原始图像的尺寸相同,并将像素写入其中,而不是写回原始的 BufferedImage。

BufferedImage targetImage = new BufferedImage(img.getWidth(),
        img.getHeight(),  BufferedImage.TYPE_3BYTE_BGR);

将像素写入此图像...

targetImage.setRGB(x, y, p);

然后保存这个新图像..

ImageIO.write(targetImage, "jpg", f);

请注意,将彩色图像转换为灰度的更准确方法是将 RGB 像素转换为 YUV 颜色空间,然后使用亮度值,而不是 RGB 的平均值。这是因为 RG 和 B 的亮度加权不同。

于 2018-05-09T06:14:18.127 回答