Image Processing in Java – Colored Image to Grayscale Image Conversion
In this article, we will be converting a colored image to a grayscale image.
RGB Color Model – The RGB color model is an additive mixing model in which red, green, and blue light are added together in various ways to reproduce a broad array of colors.
Grayscale Images – Grayscale images, a kind of black-and-white or gray monochrome, are composed exclusively of shades of gray. The contrast ranges from black at the weakest intensity to white at the strongest.
Generally, a grayscale image uses an 8-bit representation for each pixel. By using 8-bits, we can represent values from 0 to 255. So a grayscale image in 8-bit representation will be a matrix, and the values can be anything from 0 to 255. 0 indicates black pixels, and 255 indicates white pixels, and in between different shades from black to white will come.
Note: In a grayscale image, the Alpha component of the image will be the same as the original image, but the RGB will be changed i.e, all three RGB components will have the same value for each pixel.
- Get the RGB value of the pixel.
- Find the average of RGB, i.e., Avg = (R+G+B)/3
- Replace the R, G, and B values of the pixel with the average (Avg) calculated in step 2.
- Repeat Step 1 to Step 3 for each pixel of the image.
Note: This code will not run on an online IDE as it needs an image on disk.
This article is contributed by Pratik Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.