Image processing in Python?

PythonServer Side ProgrammingProgramming

Python provides lots of libraries for image processing, including −

  • OpenCV − Image processing library mainly focused on real-time computer vision with application in wide-range of areas like 2D and 3D feature toolkits, facial & gesture recognition, Human-computer interaction, Mobile robotics, Object identification and others.

  • Numpy and Scipy libraries − For image manipuation and processing.

  • Sckikit − Provides lots of alogrithms for image processing.

  • Python Imaging Library (PIL) − To perform basic operations on images like create thumnails, resize, rotation, convert between different file formats etc.

In this section we are going to see some basics of image processing in python.

Install required library 

Our first step will be to install the required library, like openCV, pillow or other which we wants to use for image processing. We can use pip to install the required library, like −

$pip install pillow

That's it: now we can play with our image.

Image: Open() and show()

First, open the file/image and show. You can rotate the image while showing like below −

#Import required library
from PIL import Image

#Open Image
im ="TajMahal.jpg")

#Image rotate & show


As the above variable im, is a pillow object. We can retreive some information about the opened image −

>>> im
<PIL.JpegImagePlugin.JpegImageFile image mode = RGB size = 1000x667 at 0x65AB990<
>>> im.size
(1000, 667)
>>> im.format

Convert and Save() Image 

We can change the format of image from one form to another, like below −


Now if we see the folder, we have same image in two different formats.


We can change the size of image using thumbnail() method of pillow −

>>> im.thumbnail ((300, 300))

The image will change as follows:

Converting to grayscale image − convert()

We can make the grayscale image from our original colored image.

>>> TajMahal_gray ='TajMahal.jpg').convert('L')

Where "L" stands for 'luminous'.

Above example is from the PIL library of python. We can use other library like open-cv, matplotlib & numpy for image processing. Below are some of the example program to demonstrate the use of much powerful library for image processing.

Showing image in grayscale

#Import required library
import cv2
import numpy as np
from matplotlib import pyplot as plt

im = cv2.imread('TajMahal.jpg',cv2.IMREAD_GRAYSCALE)


Another way to write above program with a tick/line to mark the image.

import cv2
import numpy as np
from matplotlib import pyplot as plt

im = cv2.imread('TajMahal.jpg',cv2.IMREAD_GRAYSCALE)

plt.imshow(im, cmap = 'gray', interpolation = 'bicubic')
# to hide tick values on X and Y axis
plt.xticks([]), plt.yticks([])
plt.plot([200,300,400],[100,200,300],'c', linewidth = 5)


Published on 27-Mar-2019 11:33:51