How to change the pixel values of an Image in Python?

In this blog, we will be learning about changing the pixel values of an image in Python. For this purpose, we will have to use the Python Imaging Library (abbreviated as PIL). Now let’s see how it is going to work out for us.

Importing and installing PIL

You can add any image from your library or else you can simply use the following procedure to create a simple black image.

from PIL import Image

First import the Image package from PIL. If you get any error such as the absence of PIL (expected in Python 2.7 & above) then do the following in command prompt:

pip uninstall Pillow
pip uninstall PIL
pip install Pillow

In the next step, import it again and get started. Now we need to import a package called display from IPython so that we can display our images with ease.

from PIL import Image
from IPython.display import display

Creating or importing an image

 

Now, we create a black image for our purpose. Create a variable and store in that variable the pixel values and colour code and name as given below:

MyImg = Image.new( 'RGB', (250,250), "black")
#Imported_Img = Image.open('ImageName.jpg') 
#use the commented code to import from our own computer

Creating a pixel map

Our goal will be changing the pixel values so that we can make it a multi-coloured image. For that, we need to create a pixel map by creating another variable ‘pixels’ and we load the image into that variable.
pixels = MyImg.load()

We now have to change pixel values of every row and column of the image (if we consider it as a matrix of pixels).

for i in range(MyImg.size[0]):        #for each column
    for j in range(MyImg.size[1]):    #For each row
        pixels[i,j] = (i, j, 100)    #set the colour according to your wish

Displaying the image

Finally, we display the image that is created after the change in pixel values.

display(MyImg)

The complete code to change the pixel values of an Image in Python

from PIL import Image
from IPython.display import display

MyImg = Image.new( 'RGB', (250,250), "black") 
pixels = MyImg.load() # creates the pixel map
display(MyImg)        # displays the black image
for i in range(MyImg.size[0]):    
    for j in range(MyImg.size[1]):  
        pixels[i,j] = (i, j, 100)

display(MyImg)        # displays the changed colourful image

Also read: Plot a histogram for an Image in PIL in Python

2 responses to “How to change the pixel values of an Image in Python?”

  1. Gangadhar Dandia says:

    This is outstanding application and learning.

  2. Aden says:

    for i in range(MyImg.size[0]): #for each column

    in this line should n’t it be for each row
    ?
    after that we iterate over columns then next row

Leave a Reply

Your email address will not be published. Required fields are marked *