我目前正在尝试使用Java处理图像,尝试使用BufferedImage类将RGB图像转换为灰度图像。
我的想法是获取每个像素的RGB值,并将它们设置为(R+G+B)/3:
BufferedImage image = ImageIO.read(new File(file));
int[] pixel;
int r, g, b;
for (int y = 0; y < image.getHeight(); y++)
{
for (int x = 0; x < image.getWidth(); x++)
{
pixel = image.getRaster().getPixel(x, y, new int[3]);
r = pixel[0];
g = pixel[1];
b = pixel[2];
int gr = (int)((r+g+b)/3);
String hex = Integer.toHexString(gr)+Integer.toHexString(gr)+Integer.toHexString(gr);
int i = Integer.parseInt(hex, 16);
image.setRGB(x, y, i);
}
}
ImageIO.write(image, "jpg", new File("im2.jpg"));
结果如下:
最终结果如下:
虽然这可能是将图像转换为灰度图的最低效方法,但我不知道为什么会发生这种情况。我错过了什么吗?