Convert image to gray scale image using python and pillow

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.

Installation

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.

  1. Each image consists of smallest unit called as pixel.
  2. Each pixel is made up (R,G,B) values which are the primary colours.
  3. 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.

Code

The following code snippet converts any image to grey scale image.

gray scale image

Steps involved

  1. Open the image using the pillow library and load it to the memory.
  2. Get the height and width using the size method.
  3. Create a copy of the image with same size and mode.
  4. Iterate the pixels one by one.
  5. Each pixel value is a tuple of three values(R, G, B)
  6. Get the average of these three values and floor it to get an integer value.
  7. 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.

new_image.save('new.png')
original image
gray scale image

The above code gets the first image as the input and produces the next image as the output.

Happy coding!