How to manipulate the pixel values of an image using Python ?
It is well known that a color image is a collection of various pixels. And if we change the pixel value the image will turn into an image of a different color. Doing this tedious task manually is awful as an image might contain millions of pixels. So we will write a Python script that will easily complete this task.
While developing predictive models of image data we sometimes need to manipulate the image. And for this purpose python has an amazing library named Python Imaging Library(PIL). This library contains some method with which we can extract the pixelmap of an image and simply with the help of loops we can iterate over each of its pixels and change its pixel value according to our need. A pixel is the smallest base component of an image and similarly, a pixel map can be thought of as a matrix of pixels that represents an image.
- First, we need an image file as input. This image file can either be created through the Image.new() method or be imported from the local machine through the Image.open() method. Both the cases have been shown in the below example. (Not mandatory but for our convenience, we have saved the image with the name of “input.png” especially to look at the difference.)
- Secondly, we need to extract the pixel map of the input image(the matrix of pixel values) with the help of the Image.load() method so that we can manipulate our desired pixel. The Image.size method returns the width and height(column and row) of the image(pixelmap or matrix). Then with the help of loops, we will iterate and change our desired value of the pixel.
- Finally, after updating or changing the pixel value we will get the output image. (Again not mandatory but for our convenience, we will save the output image with the name of “output.png” with the help of the Image.save() method. We can also see the image on the output screen using the Image.show() method.
Example 1: Use an image from the local machine and turn half of it into a grayscale image
The average formula to change an image into a grayscale image:
G = (R+G+B) / 3
The above formula is theoretically correct but a more improved formula(The weighted method, also called luminosity method, weighs red, green, and blue according to their wavelengths) is as follows:
G = (0.299R + 0.587G + 0.114B)
Note: Here the half of the image has been converted to grayscale, but the full can be done using the same code just by changing (width//2) to (width). To know more about this refer Image.getpixel() method.
Example 2: Manipulate pixel values
Please Login to comment...