Friday, December 27, 2024
Google search engine
HomeLanguagesHow to manipulate the pixel values of an image using Python ?

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.

Approach

  1. 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.)
  2. 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.
  3. 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)

Input image:

Input image

Python3




from PIL import Image
  
# Import an image from directory:
input_image = Image.open("gfg.png")
  
# Extracting pixel map:
pixel_map = input_image.load()
  
# Extracting the width and height 
# of the image:
width, height = input_image.size
  
# taking half of the width:
for i in range(width//2):
    for j in range(height):
        
        # getting the RGB pixel value.
        r, g, b, p = input_image.getpixel((i, j))
          
        # Apply formula of grayscale:
        grayscale = (0.299*r + 0.587*g + 0.114*b)
  
        # setting the pixel value.
        pixel_map[i, j] = (int(grayscale), int(grayscale), int(grayscale))
  
# Saving the final output
# as "grayscale.png":
input_image.save("grayscale", format="png")
  
# use input_image.show() to see the image on the
# output screen.


Output:

Output image.

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

Input Image:

Input image.

Python3




from PIL import Image
  
# Create an image as input:
input_image = Image.new(mode="RGB", size=(400, 400),
                        color="blue")
  
# save the image as "input.png"
#(not mandatory)
input_image.save("input", format="png")
  
# Extracting pixel map:
pixel_map = input_image.load()
  
# Extracting the width and height
# of the image:
width, height = input_image.size
z = 100
for i in range(width):
    for j in range(height):
        
        # the following if part will create
        # a square with color orange
        if((i >= z and i <= width-z) and (j >= z and j <= height-z)):
            
            # RGB value of orange.
            pixel_map[i, j] = (255, 165, 0)
  
        # the following else part will fill the
        # rest part with color light salmon.
        else:
            
            # RGB value of light salmon.
            pixel_map[i, j] = (255, 160, 122)
  
# The following loop will create a cross
# of color blue.
for i in range(width):
    
    # RGB value of Blue.
    pixel_map[i, i] = (0, 0, 255)
    pixel_map[i, width-i-1] = (0, 0, 255)
  
# Saving the final output
# as "output.png":
input_image.save("output", format="png")
  
# use input_image.show() to see the image on the
# output screen.


Output:

Output image

RELATED ARTICLES

Most Popular

Recent Comments