Image Processing






Basics



PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. It was developed by Fredrik Lundh and several other contributors. Pillow is the friendly PIL fork and an easy to use library developed by Alex Clark and other contributors. We’ll be working with Pillow.

1. Installation

Linux: On linux terminal type the following:

$ pip install Pillow

Installing pip via terminal:

$ sudo apt-get update
$ sudo apt-get install python-pip

Windows: Download the appropriate Pillow package according to your python
version. Make sure to download according to the python version you have. We’ll be working with the Image Module here which provides a class of the same name and provides a lot of functions to work on our images.To import the Image module, our code should begin with the following line:

from PIL import Image

 

2. Operations on Image
2.1 Reading or Opening an Image

To read image from current folder, use following code

img=Image.open("abc.jpg")

here 'img' is the matrix or variable in which we can store the image. Here in Image.open(), 'I' is the capital im image because Image is the class.

 

2.2 Displaying an Image

To display opened image, use following code

img.show()

 

2.3 Writing Image

To write an image in current folder, use following code

img.save("xyz.jpg")

Example: Simple python program to read, write and display an Image.

from PIL import Image           # Improting Image class from PIL module

# Reading an Image from current folder
img=Image.open("abc.jpg")  

# Displaying an opened Image
img.show()

# Saving Image in current folder
img.save("xyz.jpg")

Output:

 

2.4 Retrieve Information of an Image

The instances of Image class that are created have many attributes, one of its useful attribute is size.

from PIL import Image
img=Image.open("abc.jpg")
print(img.width)
print(img.height)
print(img.format)
print(img.info)

 

2.5 Rotating an Image

To rotate an image, provide an angle as a parameter.

from PIL import Image
img=Image.open("abc.jpg")
img=img.rotate(45)
img.show()

 

2.6 Resizing an Image

Image.resize(size)- Here size is provided as a 2-tuple width and height.

from PIL import Image
img=Image.open("abc.jpg")
img=img.resize((300,300))
img.show()

 

Lab Assignment:

Write a program to perform following operation on Images
a. Read and Display an Image

b. Write an Image

c. Retrieve size of image

d. Save changes in image

e. Rotating an Image

f. Resizing an Image