【发布时间】:2018-05-10 07:45:08
【问题描述】:
我正在尝试创建一个程序,为我的计算机科学课程在所选图像上应用灰度滤镜。 我在教程中找到了以下代码,它演示了灰度算法,其中图像中每个像素的 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
问题是,程序没有在某些图像上正确应用灰度滤镜。例如,代码可以正确地对this 图像应用过滤器,创建grayscale image。但是下面的图像 rainbow 看起来像 this 应用了灰度滤镜。
为什么会显示红色、绿色、蓝色和粉红色,并带有过滤器?我的理解是,当一个像素的R、G、B值相同时,应该创建一个灰色?
【问题讨论】:
-
我不确定算法有什么问题,但考虑过使用
ColorConvertOp代替吗? As demonstrated here -
您是否可以使用索引彩色图像而不是 rgb 图像?
-
@MadProgrammer 谢谢你的建议,我看看能不能用!但我仍然很好奇为什么算法不起作用。
-
@Shadowzee 如何检查它是否是索引彩色图像? (抱歉这个菜鸟问题)
-
@user9761831 我真的没有想法
标签: java image-manipulation grayscale