Image processing using Python Pillow
In this article, you will learn how to process and manipulate an image using the Python Pillow or PIL library.
Image processing is the technique of performing some operations on an image, in order to get an improved image or to extract some useful information from it. It is a type of signal processing in which the input is an image and the result may be an image or qualities or features related to that image. It is used to find various patterns and aspects in images. It helps to improve images for human understanding.
The Pillow and PIL (Python Imaging Library) are the same. The PIL was used with Python2. Pillow is a fork of the PIL repository which is currently compatible with Python3. This library is mostly used for image opening, processing, and transforming. It is available for Windows, Mac OS X and Linux. With the use of this library, we can also perform several image operations, like resizing, cropping, file conversion, rotating, and much more.
Pillow Installation
To install Pillow on windows, open a terminal window and run the following command.
pip install pillow
This library is pre-installed on my working system, so it returns the following-
Requirement already satisfied: pillow in c:\python37\scripts\projects\env\lib\site-packages (7.0.0)
Check Installation of Python Pillow
We can check the successful installation of Pillow by printing the installed version.
import PIL
print('Pillow Version:', PIL.__version__)
(env) c:\python37\Scripts\projects>pillow1.py
Pillow Version: 7.0.0
Python Pillow Open Image
Now, let's know how to open an image using the Pillow library. The most common module for image handling is the Image module. This module has inbuilt functions, such as loading images or creating new images, etc. Here, we have used the open() method of this module to read an image. The show() method is used to display the image.
from PIL import Image
img = Image.open('mountain.jpg')
img.show()
In the above example, we provide only the image name as the location of the image is in the same directory as the Python program, otherwise the full path of the image should be provided.
Python Pillow Get Image Mode
One image contains one mode. The image module provides the mode attribute, which tells the type and depth of the pixel in the image. Each pixel uses the full range of the bit depth. A 1-bit pixel has a range of 0-1, an 8-bit pixel has a range of 0-255, and so on. There are different modes provided by this module.
Mode | Description |
1 | 1-bit pixels, black and white |
L | 8-bit pixels, Greyscale |
P | 8-bit pixels, mapped to any other mode using a color palette |
RGB | 3×8-bit pixels, true color |
RGBA | 4×8-bit pixels, true color with transparency mask |
CMYK | 4x8-bit pixels, color separation |
I | 32-bit signed integer pixels |
F | 32-bit floating point pixels |
The given code returns the mode of the image using the mode() method.
from PIL import Image
img = Image.open('mountain.jpg')
print(img.mode)
Output of the above code:
RGB
Python Pillow Convert Image Mode
Python Pillow provides convert() method to convert the current mode to others. Different image mode tells the data of each image pixel differently. The following code reads an image and convert it to the specified modes. We have also saved the generated grayscale image using the save() method.
from PIL import Image
img = Image.open('mountain.jpg')
modes = ["1",'L','P','RGB','RGBA']
for m in modes:
file_name = str(m)
img_cov = img.convert(m)
#show image
img_cov.show(file_name)
Output of the above image:Image mode 1 | |
Image mode L | |
Image mode P | |
Image mode RGB | |
Image mode RGBA |
Python Pillow Get Image Size
The size attribute provides the size of the image. It returns a tuple that contains width and height.
from PIL import Image
# Open Image
img = Image.open('mountain.jpg')
# getting image size
print(img.size)
(560, 334)
Python Pillow Get Image Format
The format attribute provides the format of the image file.
from PIL import Image
# Open Image
img = Image.open('mountain.jpg')
# getting image format
print(img.format)
JPEG
Python Pillow: Cropping Image
The image.crop() is used to crop the image. It crops a region from an image which is defined by a 4 tuples (left, upper, right, lower).
from PIL import Image
# Open Image
img = Image.open('mountain.jpg')
# Size of the image in pixels
width, height = img.size
# Setting the points for cropped image
left = 1
top = 2
right = 300
bottom = 300
# Cropped image of above dimension
img_cropped = img.crop((left, top, right, bottom))
img_cropped.show()
Python Pillow: Rotating Image
The Image.rotate() method is used to rotate an image. It takes rotation angle as an attribute and returns a rotated copy of the image.
from PIL import Image
img = Image.open('mountain.jpg')
cropped = img.rotate(180)
#show image
cropped.show()
Python Pillow: Create Thumbnail
To create thumbnail using Pillow is very simple. It provides a thumbnail() method that takes a tuple specifying the thumbnail size and converts the image to a thumbnail.
Python Pillow: Draw Shapes
With the use of Pillow module, we can also draw different shapes, like- rectangle, polygon, ellipse and so on. In the given example, we have drawn two rectangles, one polygon and one ellipse, using the ImageDraw module. This module provides simple 2D graphics for image objects.
from PIL import Image, ImageDraw
img = Image.new('RGBA', (200, 200), 'yellow')
idraw = ImageDraw.Draw(img)
idraw.rectangle((10, 10, 100, 100), fill='blue')
idraw.rectangle((100, 100, 250, 200), fill='cyan')
idraw.polygon([(200,10), (200, 200), (150,50)], fill = 'red')
idraw.ellipse((20, 20, 90, 90), fill = 'green', outline ='black')
img.show()
Related Articles
Geometric Transformation OpenCV PythonPython convert dataframe to numpy array
Convert Python list to numpy array
Multiply all elements in list Python
Python NumPy: Overview and Examples
Python Numpy Array Shape
Convert Python list to numpy array
Python convert dataframe to numpy array
zip function in Python
NumPy program to copy data from a given array to another array
Multiply all elements in list Python
Remove element from list Python
Inverse of a matrix in Python
Python Contour Plot Examples
Python iterate list with index
Python add list to list
Prettytable in Python
Python dict inside list
Convert array to list Python
Python Matplotlib Bar Plot