Python Pillow TutorialAs technology emerges day by day, digital images can be an indispensable source of receiving data. We encounter a lot of digital images in daily life. However, these pictures can be related to anything. In the programming world, we can process digital images using various libraries or tools. In this article, we will learn about one of the popular tools of Python is Pillow. However, Python provides many other useful libraries such as OpenCV, Python Image Library (PIL), and Scikit-image. This article completely focuses on the Python Pillow module (PIL). Before dive deep into this topic, let's understand image processing. What is Image Processing?Image processing is a method of analyzing and manipulating digital images. The main goal is to extracting some information that can be used somewhere else. Let's make it simple to understand with a real-life example. For example - Nowadays, CCTV cameras are instated in the traffic light that capture digital images, identify the vehicle's number plate, and check whether the vehicle violated the traffic rules or not. All this process is related to image processing. IntroductionPython Pillow module is built on top of PIL (Python Image Library). It is the essential modules for image processing in Python. But it is not supported by Python 3. But, we can use this module with the Python 3.x versions as PIL. It supports the variability of images such as jpeg, png, bmp, gif, ppm, and tiff. We can do anything on the digital images using the pillow module. In the upcoming section, we will learn various operations on the images such as filtering images, Creating thumbnail, merging images, cropping images, blur an image, resizing an image, creating a water mark and many other operations. Installation of PillowBefore start working with Python, we need to install the pillow library to our local machine. We can do it by typing the following command in the terminal. If pip is already installed in the system, it will simply show the "requirement already satisfied". Using the Image ModulePython pillow library is used to image class within it to show the image. The image modules that belong to the pillow package have a few inbuilt functions such as load images or create new images, etc. Opening, Rotating and Displaying an ImageOpening an image is a basic operation of the image processing. We import the image module from the PIL library to load the image. It provides the Image.open() method, which takes an image filename as an argument. This method returns the image object. We can make any modification to image object which can be saved to an image with the save() method. Once the image is open, we can perform operations as resize, crop, draw or many others. Let's understand the following example. Example - Output: Image after Rotation - Explanation The above code displayed the original and rotated image using the standard jpeg display utility. If we run the above code in the Jupyter notebook then the output will be shown in the local machine image gallery. Attributes of Image ModuleThe Image class contains some attributes to manipulate the image object. Let's understand these attributes using one by one. Image.filemnameThe Image.filename function returns the name of the image. Output: 'C:\\Users\\DEVANSH SHARMA\\Downloads\\car.jpg' Image.formatThis function is used to get file format of the image file such as 'JPEG', 'BMP', 'PNG', etc. Output: 'JPEG' Image.modeThe above method returns the pixel format used by the image. Typing variables are '1', 'L', 'RGB', or 'CMYK'. Output: 'RGB' Image.sizeThe Image.size function returns the tuple that contains height & weight of the image. Output: (480, 320) Image.widthThis method returns the width of the image. Output: 480 Image.heightThis method returns the width of the image. Output: 320 Image.infoThis method returns a dictionary holding data associated with the image. Output: {'jfif': 257, 'jfif_version': (1, 1), 'jfif_unit': 0, 'jfif_density': (1, 1), 'progressive': 1, 'progression': 1} Working with ImagesPython pillow module makes very simple to work with the images. We can use PIL.Image modle function. Let's see the syntax. Syntax - In the above syntax -
Consider the following example. Example - In the following example, we will open an image in .jpg format. First, we will display the image and then save it with another file format. The above code will display the actual and rotate image at 45 degree. Explanation - In the above code, we have imported the Image module from PIL library, called Image.open() function to read an image. The Image.open() function returns an image object. This method takes a filename(string), a path object or an image(file) object. Saving an ImageThe Image module provides the save() method to save the image to file. It takes a filename, a file object that has been opened to write. Let's understand the following syntax. Syntax &ndash In the above syntax -
If we sum up the above syntax, the file saves based on the given filename. If we don't specify the format, it is based on the current filename extension. In the above example, it keeps the file based on the file extension the image type. For example - The code will save as a png file in our current working directory. We can also obviously identify the file type as a second parameter. Let's see the following line. Creating ThumbnailsThumbnail is images of equal height and width. Sometimes, we need to create a thumbnail to specify the actual image. The pillow library provides thumbnail() function. This method transforms the actual image to contain a thumbnail version of it. The size of the thumbnail will not be same as the given size. The thumbnail() estimates a suitable thumbnail size to preserve the aspect of the image. We need to call another method draft() method, configuring the file reader and, finally, resizing the image. Let's see the following syntax. Syntax - The above syntax -
Let's understand the following example. Example - Output: Explanation - In the above code, we have defined the thumbs() function that contains the try-expect to handle any occurrence. In the try block, we have opened an image which we want to modify as thumbnail. Then, we have called the thumbnail() function to the image object and we have passed the thumbnail size. Somehow, if the try block would through an error, it will jump to except block where we defined the IOError exception. Merging Images Using PillowWe can paste an image onto another one. Pillow library provides merge() function which takes a mode and tuple of the images parameters. Then, it associates them with a single image. Let's see the following syntax. Syntax - In the above syntax -
Let's understand the following example. Example - Output: When we execute the above code, we can observe the difference between original image and the image with merge the RGB bands. Merging Two ImagesMerging two images is the same as above. First, it requires to create an image object for the essential image using the open() function. One point should be remembered by developer; both images must be the same size before merging them. Then we create empty images using the Image.new() function, we paste the images using the paste() function. After that, we save and display the resultant image using the save() and show() functions. Let's understand the following example. Example - Output: Explanation - In the above code, we have imported the Image module from the PIL library. We opened two images to merge them with each other. Before perform the merge operation, we need to make sure both images should be the same size. We made the size of the first image as the second image. Then, we used the paste() method to merge them. Blur an Image Using PillowBlurring an image is a method of decreasing the level of noise in the image by applying a filter to an image. It is the most important aspect of image processing. The pillow library offers the ImageFilter class that contains several standard image filters. In this section, we will discuss various techniques of blurring images. These techniques are mentioned below.
The Image.filter() method will use the techniques mentioned above to apply the filters' images. Simple BlurIn the simple blur, the blurring effect is applied to the image as specified through a specific kernel. Let's see the following syntax. Syntax - Let's understand the following example. Example - Output: Original Image - Blurred Image - We have opened two standard images to perform blur operation. We can see the difference between the original image and the blurred image. Box BlurThe Box Blur filter uses the 'radius' as a parameter. It is directly proportional to the blur value. Syntax - In the above syntax -
Let's understand the following example. Example - Original Image - Box Blurred Image - Gaussian BlurThis filter works the same as box blur but slight changes in its algorithm. It also takes the radius parameter. We can generate a different intensity of Gaussianblur image by changing the radius value. Syntax - Let's understand the following example. Example - Output: Original Image - Gaussian Blurred Image - Creating a Watermark using PillowWe all may see a tiny text on the bottom of the online photos which is called watermark. It is an excellent way to protect images and prevent their misuse. Watermark does not only protect from misuse but also provide the copyright to our creative photos. So, it is preferred to add a watermark to the image, before sharing to the social media. It is kind of text or logo overlaid on the photo that have a small identity of the owner or who owns the rights to the photo. With the Python Pillow library, we can add the watermark to the image very easily. This library provides the Image, ImageDraw and ImageFont module. Let's understand the following example. Example - Explanation - In the above code, we have imported the Image, ImageDraw and ImageFont modules from the pillow library where the ImageDraw module enhances the functionality to draw 2D graphics to the image. The ImageFont module is responsible for adding font functionality while writing watermark. We created an image object where we will apply the watermark. The image object passed to the Draw() method; we wrote the watermark and saved it to the text variable. We can also set the font-family and font-size as we have set 'Times New Roman' and font-size 25. Then, we calculated the x, y coordinate to specify the text position in the image. Once we calculated the coordinate, we drew the watermark in the bottom right corner. Apply Color to the ImagePillow library provides the ImageColor module that contains colors in the several formats. It also has the converter from CSS3-style color specifiers to RGB tuples. Let's have a look at the color names which are supported by the ImageColor module. The first format is Hexadecimal color specifiers, specified as #rgb or #rrggbb. For example, #00ff00 denotes pure green. The second format is #00ff00 hex color, red value is 0 (0% red), green value is 255(100% green) and the blue value of its RGB is 0 (0% blue). There are 140 standard color names in the ImageColor module. Most of the colors are supported by the Window system and most web browsers. ImageColor.getrgb() MethodThis method is used to convert a color string to an RGB tuple and it raises a ValueError exception in case of string cannot be parsed. Let's see the following syntax. Syntax - In the above syntax -
Let's understand the following example. Example - Output: (0, 0, 255) (255, 0, 0) As we can see in the above code, the getrgb() method taken the color name and returned the RGB values. Example - 2 ImageDraw ModuleThe ImageDraw module is a very important component of the Pillow library. We can provide some simple 2D graphics support for image object. This module helps create new images, provides some additional touches to the image, and creates some graphics. It also supports the annotation of text and drawing of shapes. ImageDraw module uses the origin of the two-dimension co-ordinate which is in the upper left corner of the image. It supports the various fonts for the text annotations such as bitmap, OpenType, or TrueType. Let's understand the following example. Example - Output: Image Sequence in PillowImage Sequence is equivalent to the animation formats support by the Python PIL library. FLI/FLC, GIF and some new formats are the maintained by sequence formats. TIFF files can contain more than one frame as well. PIL uploads the image in the sequence like first frame is loads according to the image sequence. We can use seek() and tell() methods to move the different frames. Let's understand the following example. Example - Output: raise EOFError EOFError Explanation - In the above code, we can see that the EOFError exception is thrown when the sequence ends. To overcome that situation, we can create a sequence iterator class. A sequence iterator class Writing Text on the Image Using PillowThis is different from the creating a watermark. We can write text to the image by passing the location where we want to write text on the image. We can pass the multiple parameters to text method. Let's understand the following example. Example - Output: Flip and Rotate Image Using PillowSometimes, we need to perform a few basic operations such as rotating and flipping the image. These operations are helpful to get the insight form the existing image, it also enhance the visibility of the image. Pillow library allows us to flip and rotate an image very easily. We will use the transpose (method) function from the image module to perform the flip operation. Some of the most common methods are given below.
Let's understand the example how to flip an image horizontally. Example - Output: Original Image Flipped Image - Explanation - In the above code, we have read the image and flipped it horizontally. Both images original and flipped displayed image using standard JPG display utility. Example - 2 Vertically Flipped Image Output: Original Image - Flipped Image - Let's understand another example of rotation Example - 3 Output: Original Image - Rotated Image - |