I am trying to create a program that applies a grayscale filter over a chosen image for my computer science class. I found the following code in a tutorial, it demonstrates the grayscale algorithm where the R, G, and B values of every pixel in the image is replaced with the average of the RGB value.
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
The problem is, the program does not properly apply the grayscale filter over certain images. For example, the code can properly apply a filter over this image, creating a grayscale image. But the following image of a rainbow looks like this with the grayscale filter applied to it.
Why are red, green, blue, and pink showing with the filter over it? My understanding is that when the R, G, and B values of a pixel are the same, a gray colour should be created?