In this article we are going to convert a normal image into its gray scale format using python and pillow.
What is a gray scale image?
A grayscale (or graylevel) image is simply one in which the only colors are shades of gray. The reason for differentiating such images from any other sort of color image is that less information needs to be provided for each pixel.
We need the pillow library from python to begin with. This can be installed using pip as
pip install pillow
Things to know
These are some of the things to know before starting with the code.
- Each image consists of smallest unit called as pixel.
- Each pixel is made up (R,G,B) values which are the primary colours.
- A gray scale image is one in which each pixel has the same values for R,G,B
It will be easier to explain the rest of the things from the code below.
The following code snippet converts any image to grey scale image.
- Open the image using the pillow library and load it to the memory.
- Get the height and width using the size method.
- Create a copy of the image with same size and mode.
- Iterate the pixels one by one.
- Each pixel value is a tuple of three values(R, G, B)
- Get the average of these three values and floor it to get an integer value.
- Using the putpixel() method, assign the new R,G,B values to the new image.
I am using the show() method to just display the image. You can also use the save() method to save the image instead of displaying it.
The above code gets the first image as the input and produces the next image as the output.