Negative Transformation of an Image using PIL

In this tutorial, you will learn how to do the negative transformation of an Image using PIL in Python. PIL stands for Python Imaging Library. It is used to perform some basic operations on Images in Python. Hence for this task, we have to use Image Class from the PIL. So, the very first line of the script will be as follows

from PIL import Image

Here, Image Class consists of various attributes and methods. We need open, show, getpixel and putpixel Methods to open an Image, to view an image, to get pixels of specified Image and to replace the Pixels into the Image respectively.

Perform negative transformation of an image in Python

So let’s have a look at opening an Image. It can be done as follows.

img=Image.open("Path_to_your_Image")

Here, img is the Image Object for the specified Image which is located at “Path_to_your_Image”. Let’s have a glance over the Negative Transformation of Colours in an Image.

Negative Transformation:

As we know that in RGB colour Model, Every color has its decimal indices ranging from 0-255. 0 refers least and the 255 refers the highest. i.e. (255,255,255) indicates white. Similarly (0,0,0) indicates black. We are supposed to perform the Negative Transformation of the Colour which means the color gets inverted as follows.

Let Colour X is represented as (r,g,b)=(100,100,100). It can be transformed as follows

R=255-r =255-100=155         =>   R=155

Similarly, G=155 and B=155

Hence Negatively Transformed Colour Indices of X are (R,G,B) =(155,155,155)

So, let’s implement Negative Transformation of Colours for each Pixel of an Image.

Example:

from PIL import Image
img=Image.open("Path_to_your_Image")
w,h=img.size     # returns Width and Height of an Image
for i in range(w):
    for j in range(h):
        r,g,b=img.getpixel((i,j))
        r=255-r
        g=255-g    # Since 255 is the Highest Index
        b=255-b
        img.putpixel((i,j),(r,g,b))
img.show()  # To display Image

Input: The input for the above code will be as follows

color image

Output: The output of the above code will be as follows

Negative Transformation of an Image using PIL

Hence, In this way, we can perform the Negative Transformation of an Image using PIL in Python.

For further reference, read also Dimensions of an Image in Python

Leave a Reply

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