Python Pillow (PIL Fork) Library Image Processing Tutorial

By Sruthy

By Sruthy

Sruthy, with her 10+ years of experience, is a dynamic professional who seamlessly blends her creative soul with technical prowess. With a Technical Degree in Graphics Design and Communications and a Bachelor’s Degree in Electronics and Communication, she brings a unique combination of artistic flair…

Learn about our editorial policies.
Updated April 29, 2024
Edited by Vijay

Edited by Vijay

I'm Vijay, and I've been working on this blog for the past 20+ years! I’ve been in the IT industry for more than 20 years now. I completed my graduation in B.E. Computer Science from a reputed Pune university and then started my career in…

Learn about our editorial policies.

Get familiarized with the most popular methodologies for leveraging PIL Fork. Delve deep into the distinct functionalities of Python Pillow (PIL Fork) Library Image Processing with code examples:

The pillow module allows for merging images, creating thumbnails, blurring an image, resizing, creating a watermark, cropping images, and performing many other operations.

PIL is the most lightweight image processing tool and it can be used for tasks like editing, creating, or saving images. Pillow has powerful image processing capabilities and gives efficient internal representation. Python Pillow library acts as a good foundation tool for image processing.

Python Imaging Library – PIL Fork Review

Python Pillow Featured Image

To enhance the look of an image, various filters are used to upgrade the quality of an image. By applying these filters, the feel and look of an image can be completely transformed.

There are two types of filters i.e. Parameterized and Non-Parameterized filters. By parameterized filters, distinct parameter values of an image can be changed by modifying the properties of filters.

Image-Processing-in-Python-With-Pillow

[image source]

PIL Features

Here, we are discussing distinct functionality features of PIL for image processing.

Rotating an Image

The image can be rotated as per the need. After rotating the image, the software fills the areas with no pixel values with completely transparent pixels. The Python pillow library code can be run on the Jupyter Notebooks.

When the code is successfully executed, the image is delivered with the rotation effects as an output. Here, we have discussed some of the common attributes that can be used while rotating an image:

  • Angle: The angle can be calculated as Angle = angle divided by 360. Through it, if an image needs to be rotated through a certain degree, then the angle attribute can be added to the code.
  • Resample: The word resampling means combining interpolation and decimation to change the sampling rate by a rational factor. Specifically, for image processing, resampling is a filter that can manipulate the images.
  • Expand: Expanding the output image is necessary for holding the entire rotated image. It is worth noting that the expanded images consistently undergo rotation. The expanded images do not undergo translation.
  • Translate: For the post-rotation translation of an image, it is used. After completion of the rotation, the image is transformed to a certain degree of angle.
  • Fill color: It is an optional color used for coloring the outside area of an image. If no color is required outside the image, then the color can be put as blank.
  • Returns: The image is returned as an object. class: PIL.Image.Image is the functional operation for returning the value.
  • Centre: As a centre, the origin is marked at the upper left corner. By default, it is considered the centre of an image.

This code can rotate an image:

For importing from the Python image processing library
From PIL import image

For creating an image object from an image

colorImage =Image.open (“/Image.jpg”)

For rotating it by 30 degrees

Rotated = colorImage.rotated (30)

For displaying the original image

colorImage.show ()

For displaying the image rotated by 30 degrees

rotated.show ()

Output:

Rotationg an Image

Flipping an Image

Leveraging the transpose function, the image can be flipped and rotated in any direction. To increase the visibility and quality of an image, the flipping and rotating operations are helpful.

Below are some of the basic operations that you can use to perform flipping operations on an image:

#1) FLIP_LEFT_RIGHT: For rotating an image in a horizontal direction, the image can be flipped using this function. This functionality operation generates the mirror image.

Import required image module
For importing PIL image
Open already existing image 
imageObject = Image.open (“images/sample.png”)
For doing a flip of left and right 
hori_flippedImage =
imageObject.transpose (Image.FLIP_LEFT_RIGHT)
For showing the original image
imageObject.show ()
For showing the horizontal flipped image 
hori_flippedImage.show()

#2) ROTATE_90: For rotating an image through 90 degrees, we can use this functionality feature. The image can be rotated 90 degrees clockwise as well as anticlockwise. Specifically, the direction needs to be mentioned.

Import required image module
For importing PIL image 
Open an already exisiting image 
imageObject = Image.open (“images/sample.png”)
Show the original image 
imageObject.show ()
Show 90 degree flipped image 
degree_flippedImage = imageObject.transpose (Image.ROTATE_90)
degree_flippedImage.show ()

#3) ROTATE_180: By leveraging this functionality, the image can be rotated to 180 degrees in any direction.

#4) ROTATE_270: It rotates the image 270 degrees in the clockwise direction. If the image is rotated 90 degrees in a clockwise direction, then also it makes the same sense.

#5) FLIP_TOP_BOTTOM: For flipping the image in the vertical direction, we can use this function. The top of the image will become the bottom and the bottom of the image will become the top as an output.

Import required image module
From PIL import image 
Open an already existing image 
imageObject = Image.open (“images/sample.png”)
flip of left and right 
hori_flippedImage =
imageObject.transpose (Image.FLIP_LEFT_RIGHT)
Show the original image 
imageObject.show ()
Show vertically flipped image 
Vert_flippedImage =
imageObject.transpose (Image.FLIP_TOP_BOTTOM)
Vert_flippedImage.show ()

#7) TRANSPOSE: Using the transpose function, the rows and columns can be transposed. The top-left pixel is considered as the origin. It will remain the same after the transposed function is operated.

#8) TRANSVERSE: Using the transverse function, the rows and columns can be transposed. Only the bottom left pixel will remain in the same place in the original and modified image.

Leveraging the code written below, the transpose operation can be implemented on an image:

Perform a flip of left and right

hori_flippedImage-imageOject.transpose (Image.FLIP_LEFT_RIGHT) 

These are some of the most common operations for flipping or rotating an image. But, if you want to rotate an image through a specific degree, then using the below-mentioned code it can be made easily rotated or flipped. With additional optional parameters, customization for rotating an image in terms of expansion and orientation can be done.

Rotated_img = img.rotate (50) 
Rotated_img.show ()

Input and Output – Image After Flipping

Input and Output - Image After Flipping

Resizing an Image

The quality of an image either upgrades or downgrades when interpolation happens at the time of resizing or cropping. Hence, resizing an image requires careful and precise adjustments to preserve its quality.

With the functions of resize () and crop(), the images can be cropped and resized as per the need. In cropping, there are 4-tuples, i.e. top, bottom, left, and right. You can crop all four sides of an image. In the Pillow Library, the origin is considered to be the upper left corner.

Here are a few attributes that are useful while cropping or resizing an image:

  • Size: The size module allows for identifying the width and height of the pixels used in an image. By changing the width and height of an image, the resolution of an image also gets changed.
  • Returns: It returns the image as an object. Class: PIL.Image.Image is the function operational for obtaining the value as an object in an image.

The code written below can be used for resizing an image:

Importing image class from PIL module 
from PIL import image 
Open a image in RGBA mode
Im = image.open (r’’cat.png’’)
Size of the image in pixels 
(size of original image)
Width, height =im.size 
Setting the points for cropped image 
Left =6
Top = height /5 
Right = 165 
Bottom = 4*height /5 
Cropped image of above dimension 
(It will not change original image)
Im1 = im.crop((bottom, top, right, left))
Show the image in image viewer 
Im1.show ()

There is an additional operational parameter reduce(), for controlling the re-sampled image. Apart from that, for achieving the maximum size of an image, the thumbnail() function is used.

Input and Output – After Resizing

Input -2
Output -2

Saving an Image

By using the save() method, you can save the desired image using the image filename and extension. If you use the .show() functionality, it will save the image as a temporary file in the operating system. Users can use different syntaxes to save an image file.

Mentioned here are a few of them:

  • Return Value: Through it, we can get the return value. In the return value, we can expect an image.
  • Fp: The filename, path, or file object can be represented as fp. Through this syntax, the location or path of an image can be obtained.
  • Format: It can know the supporting format of an image.
  • KeyError: When the filename cannot be determined by the output of the image format, then it represents KeyError.
  • IOError: If the location of a file can’t be found, then IOError is displayed. Usually, due to an incorrect file name or location, this error is generated.

Edge Detection: The edges of an object in an image can be determined using an algorithm. With the assistance of edge detection kernels, automatically the edges in an image can be detected. Through the ImageFilter module, a pre-defined kernel can be achieved. Before processing the edge detection filter on the image, it needs to be converted into grayscale.

The code mentioned below can be used for applying an edge detection filter:

from PIL import image, ImageFilter
opening an image
im = image.open (r’’C: \Users \ System-PC \Downloads\shape.jpg’’)
image = image.open (r’’shape.jpg’’)
converting the image to grayscale, as edge detection 
requires input image to be of mode = Grayscale (L)
image =image.convert (“L”)
detecting edges on the images using the argument 
imageFilter.FIND_EDGES
image = image.filter (Image.Filter.FIND_EDGES)
saving the image under the name Edge_shape.jpg
image.save (r”Edge_Shape.jpg”)
Edge detection

Image Smoothening: Leveraging the image smoothing filter ImageFilter.SMOOTH, the edges of an image can be smoothened.

For the smoothening of an image, we can write the following code:

from PIL import image, image filter 
open the image 
Image =Image.open (“test_sample.png”)
apply smoothening filter on the image 
smoothened _image = image.filter (ImageFilter.SMOOTH)
save the smoothened image 
smoothened_image.save (“smoothened_sample.png”)

Edge Enhancement: Using edge detection kernels, the edges of an object in an image can be automatically detected. Before applying the edge detection filter, firstly the image needs to be converted into grayscale. After the conversion to the grayscale, the image can be enhanced.

Here, is the code for detecting the edges and converting the image into grayscale:

Img_gray = img.convert (“L”) 
Edges =img_gray.filter (ImageFilter.FIND_EDGES)
edges.show()

By applying the ImageFilter. SMOOTH filter, The edges of an image can be smoothened.

Below, is the Python code for filtering the edges of an image:

img_gray_smooth =img_gray.filter (ImageFilter.SMOOTH) 
edges_smooth =img_gray_smooth.filter (ImageFilter.FIND_EDGES)
edges_smooth.show ()

Merging Images: One image can be pasted into another image. By leveraging the merge function, you can merge the images. Here are the different syntaxes that can be used while merging the images.

  • Return Value: The image of an object can be returned by passing the return syntax while doing the coding.
  • Mode: Different types of modes can be used as per the size and color of the image. By using the mode syntax, the output of an image can be modified.
BytesModeStorageColor
1 bit1Stored in one pixel per byteBlack & White
8 bitL Black & White
8 bitPTrue color with a transparent mask 
24 bitRGB True color
24 bit  Color video format
32 bitRGBA Mapped to other modes using a color palette
32 bit  Color separation
24 bitLAB Lab color space
24 bitHSV Value color space
32-bit floating point pixelsIHue, Saturation 
Mapped to other modes using color paletteF  

Below is the code for merging different images:

from PIL import image
img_1 = Image.open (“number-img-0.jpg”)
img_2 = Image.open (“number-img-1.jpg”)
img_3 = Image.open (“number-img-2.jpg”)
img_4 = Image.open (“number-img-3.jpg”)
img_1 _size = img_1.size
img_2 _size = img_2.size
img_3 _size = img_2.size
img_4 _size = img_2.size
print (‘img_1 size:’, img_01_size)
print (‘img_2 size:’, img_02_size)
print (‘img_3 size:’, img_03_size)
print (‘img_4 size:’, img_03_size)
new_im = Image.new (‘RGB’, (2*img_1_size[0], 2*img_1_size[1], (550, 550, 500))
new_im.paste (img_1, (0,0))
new_im.paste (img_2, (img_1_size[0], 0))
new_im.paste (img_3, (0, img_1_size[1]))
new_im.paste (img_4, (img_1_size[0],  img_1_size[1]))
new_im.save (“merged_images.jpg”, “JPG”)
new_im_show ()

Input – Output After Merging Images

Input - Output After Merging Images

Creating Thumbnails: Through the thumbnail function, the actual image can be converted into a thumbnail. Usually, the thumbnails are of equal height and width. The size of the actual image and thumbnail will always differ.

The thumbnail image is smaller than the original image. For preserving the aspects of an image, creating the thumbnail is the best thing. Using the below syntax, we can resize and re-sample the image.

  • Return: Through the return syntax, no value can be obtained while creating a thumbnail.
  • Resample: Resampling is an optional resampling filter. PIL.Image.BICUBIC, PIL.Image.LANCZOS, Image. Nearest and BILINEAR are some of the most common resampling filters.
  • Size: This parameter defines the size (width and height) of a thumbnail.

By this code, a thumbnail image can be converted:

from PIL import image 
def thumbs ():
try:
img = Image.open (r’’C:\Users\DEVENDER YADAV\ Downloads\girl.jpg”)
img.thumbnail ((40,40))
img.save (‘images/thumbnail.jpg’)
image1 = image.open (‘images/thumbnail.jpg’)
image1.show ()
except IOError
pass 
thumb ()

Output:

output thumbnail

[image source]

Blurring an Image: By applying the Image. filter() the noise can be reduced in an image. Blurring is the image processing technique for decreasing the level of noise in an image. We can use distinct techniques for blurring an image. For example, Box Blur, Simple Blur, and Gaussian Blur are popular blurring methods.

Box Blur: Using radius as a parameter, the box blur filter can be used for blurring. If you use a radius of 20, the box blur filter will produce a more blurred image than with a radius of 5.

The following syntax can be used for blurring through the box blur technique:

  • Radius: Only in one direction the box can be defined. Therefore, through the radius factor, the image can be made blurry.
  • RRadius 1 and minnus: 9 pixels are taken for an image. One pixel in each direction.
  • Radius 0: If radius 0 syntax is passed, then it means no blurring operation is performed on the image. The image is returned as it was previously.
Import required Image library
from PIL ImageFilter, Import Image
open existing image
oriImage =Image.open (‘images/boy.png’)
oriImage.show ()
blurImage = OriImage.filter (ImageFilter.BLUR)
blurImage.show ()
save blurImage
blurImage.save (‘images/simBlurImage.png’)

Input:

input blur

Output – After applying Box Blur

output blur

Gaussian Blur: There is no big difference between Box Blur and Gaussian Blur. Only the intensity of an image is changed. It also takes radius as a parameter. Only there is a slight change in the algorithm. But in the Gaussian blur, the pixels at the center of the image receive more weightage than those at the edges.

Due to this factor, through Gaussian blur, better results are achievable than the box blur or simple blur techniques.

By applying the code mentioned below, the Gaussian blur filter can be applied:

Import Image and ImageFilter module 
From PIL import image, image filter 
Open the image 
Original Image = Image.open (r’’C:\Users \ROHIT MISHRA\Downloads \boy.jpg”)
Original_Image.show ()
Applying gaussian blur function 
blur_Image = Original_Image.filter(ImageFilter.GaussianBlur (5)))
blur_Image.show()

Input:

Input Gaussian

Output – After applying the Gaussian filter

Gaussian blur output

Simple Blur: In the simple blur technique, the image is made blurry. Leveraging a specific kernel, the blurring process is done. By using the specific syntax ImageFilter, the image can be made blur.

from PIL import image, image filter 
Open the image 
Original Image = Image.open (r’’C:\Users \ANKIT \Downloads \boy.jpg”)
Original_Image.show ()
Applying simple blur function 
blur_Image = Original_Image.filter(ImageFilter.Blur)
blur_Image.show()

Output – After applying the Simple blur filter

Output Image simple blur

Contour Filter: By applying the CONTOUR filter on the image, the blurring effect is applied to the image.

from PIL import image, image filter 
Import all the enhancement filter from pillow
From PIL.ImageFilter import (CONTOUR)
Create image object 
Img = image.open (‘images/boy.jpg’)
Applying the blur filter 
img1 =img.filter (CONTOUR)
img1.save (‘images /ImageFilter_blur.jpg’)
img1.show ()

Creating a Watermark: By creating a watermark, the images can be prevented from any misuse. By applying a logo or text behind the image, the owner of the photo leaves an identity of his copyright on the image.

Leveraging the Python Pillow library, the watermark can be easily added to an image.

Python Pillow library supports the Imagefont and ImageDraw modules. Through the ImageDraw module, the quality of the image can be increased. In the same way, by applying the ImageFont module, the font functionality can be leveraged while applying a watermark to an image.

Further Reading => Image Processing with ML and AI

Adding text feature

[image source]

By choosing a pre-configured watermark like DO NOT COPY, DRAFT, CONFIDENTIAL the image cannot be used without purchasing it. For creating the logo or mark in the background of an image, the Python Pillow library can be leveraged. The watermark can be customized by choosing the shape, size, and color of the watermark.

Here is the code that can be used for creating a watermark on an image:

Import all libraries 
from PIL import image, ImageFont, ImageDraw
for opening an image
image = image.open (“img.png”)
for creating copy of original image
watermark_img =img.copy ()
(“font type”, font size)
font = ImgFont.truetype (“Arial.ttf”,25)
Using draw function the image can be converted into editable form
draw =ImgDraw.Draw (watermark_img)
(250, 250, 250) - Black Color text 
draw.text ((0,0), “GeeksforGeeks”, (250, 250, 250), font=font)
watermark_img.show ()

Original Image

Input watermark

Output – With Watermark

Output watermark

Applying Color to an Image: Through the ImageColor module, the image can be converted into distinct color formats. Around 140 standard color names on the basis of color supported by the web browser and X Windows system are provided by the ImageColor module.

Let’s have a look at distinct color names:

Hexadecimal Color Specifiers: #00ff00 represents pure green color, #00ff00 gives red color. For the color 00ff00 the lightness value is 0.50, saturation is 1.00 and hue is 0.33. 00ff00 in this hex color, the value of red color is 0, green is 100% and blue is also 0.

By leveraging ImageColor.getrgb () method, a color string can be converted into a rgb tuple. If the string is not parsed, then ValueError is raised by the function. By using the function ImageColor.getcolor (), RGB value can be converted into grayscale value.

from PIL import image 
img =Image.open (“flower.jpg”)
img = img.convert (“RGB”)
d=img.getdata ()
new_image =[ ]
for item in d : 
change all white (also shades of yellow)
pixels to yellow
if item [0] in list (range (250,300)):
new _image.append ((300, 350, 100))
else:
new _image.append (item)
update image data 
img.putdata (new _image)
save new image 
img.save (“flower_image_altered.jpg”)

Input:

Input change colour

Output – After applying color to an image

Output change colour

Geometrical Transformations: With the function operations of resize () and rotate (), the images can be transformed. For example, if you want to rotate an image in a clockwise direction, then by simply using the code written below, you can resize and rotate an image. As per the need, an image can be easily modified in any direction and as per the requirement of size.

out = im.resize ((150,150)) 
out = im.rotate (90) #degrees counter-clockwise

Transformation of colors: Using the convert () function operation, the images of distinct pixels can be converted into another mode. Python Pillow library supports the transformation between distinct modes. Leveraging an intermediate image, the conversion from one mode to another mode can be easily done.

The current version of the mode supporting the transformation is:

  • RGB: Red, Green and Blue
  • CMYK: Cyan, Magenta, Yellow, Black or Key
  • L: Grey Scale

The grey scale can be calculated through the formula:

L =R* (299/1000) + G* (587/1000) + B* (114/1000)

from PIL import image 
With Image.open (“hopper.ppm”) as im:
Im = im.convert (“RGBA”)

Cropping an image: Through the crop () method, the image can be cropped in a rectangular or circular shape. The rectangular box is a 4 tuple of the left, right, upper, and lower pixels. Below is the code that can be used for cropping an image using the Pillow library.

  • Box: The box is a module that is mostly in the form of a rectangle. From the left, right, top, and bottom the image can be cropped.
  • Return: In the form of an image, the value is returned.

Leveraging the code mentioned below, the image can be cropped :

importing image class from PIL module
from PIL import image 
In RGBA mode the image will get opened
im = image.open (r”cat.png”)
Image size in pixels 
(original image size)
Width, height = im.size
points for the cropped image 
left = 6
top = height /6
right = 165
bottom = 4*height /5
Image of above dimensions
(The original image will remain same)
im = im.crop ((bottom, top, right, left))
Image in image viewer
im.show () 

Original Image:

imput cropping

Output – After cropping the image

Output cropping

[image source]

Adjusting Brightness and Sharpness: ImageEnhance.Brightness () is the functional operation for increasing or decreasing the brightness of an image. The enhancement factor of 0.0 gives a black image while the factor 1.0 gives the original image.

In the same way for controlling the sharpness of an image, we can use the function of ImageEnhance.Sharpness (). A factor of 2.0 gives a sharpened image, while a 1.0 factor gives an original image and 0.0 delivers a blur image.

For increasing the brightness of an image, we can use the code written below. This code allows us to increase the brightness of an image.

For importing ImageEnhance modules and Image 
From PIL import Image, ImageEnhance 
Opening Image 
Im = Image.open (r”C:\Users\Admin\Downloads\images.png”)
For creating object of Bright class 
Im = ImageEnhance.Brightness (im)
For displaying the viewer image 
Im3.enhance (2.0).show ()

Original Image:

Brightness feature

Output -After decreasing the brightness of an image

Output brightness

[image source]

To get the desired output of increasing the sharpness of an image, we can use the code mentioned below:

From PIL import Image, ImageFilter
For opening an already existing image
imageObject = Image.open (“Apricots.png”);
imageObject.show ();
Applying sharpness filter 
Sharpened 1 =imageObject.filter (ImageFilter.SHARPEN);
Sharpened 2 =imageObject.filter (ImageFilter.SHARPEN);
Show sharpened images 
Sharpened 1.show ();
Sharpened 2.show (); 

Original Image:

input sharpness

Output – After applying sharpness to an image

output sharpness

Adding Text: Many times, there is a need to add text to an image. By adding text to an image, the image becomes more meaningful and informative. The text can be of any type. Like a signature can be added or some good quotation can also be added to an image.

add text to image

[image source]

Using different types of font, size, and color the text can be added to an image. After adding the text, you can save the final image. In a couple of minutes, the text can be added to an image. The mode and size of the text are mandatory fields for writing code related to adding text to an image. Color is an optional argument while adding text to an image.

Using the Python Pillow library, we can easily add text to an image by leveraging the code as shown in the image below:

from PIL import Image, ImageDraw, ImageFont 
For opening desired image you want to add text on 
i=Image.open (‘women.png’)
By calling draw method for adding 2D graphics in an image
Im=ImageDraw.Draw (i)
mf=ImageFont.truetype (‘font.ttf’,18)
For adding text to an image 
im.text((80, 20), “Working”, fill =(0,0,0), font =mf)
Display edited image i.show()
For saving the edited image i.save (“sn.png”)

Original – Before adding text to an image

input and output for adding text to an image

Output – After adding text to an image

input and output for adding text to an image

Adjusting Color and Contrast: ImageEnhance.Contrast and ImageEnhance.Color is the functional operation for adjusting the color and contrast of an image. For balancing the color of an image, factor 1.0 gives the original color while 0.0 gives a black and white image. Similarly, for adjusting the contrast of an image, 0.0 factor gives a solid grey color image and 1.0 factor gives the original image.

Here is the code for contrasting an image. The code can be made run on the Jupyter notebooks:

from PIL import Image, ImageEnhance
For reading an image
im = Image.Open(“drawing-image.jpg”)
For making the image brightness and enhance
enhancer =ImageEnhance.Contrast (im)
factor =1.5 #increase contrast 
im_output = enhancer.enhance (factor)
im_output.save (‘more-contrast-image.jpg’)

Input:

Contrast feature

Output – After applying contrast to an image

Contrast feature

Drawing on images: Using the ImageDraw module, new images can be created. Editing on the created image can also be done using PIL. Only two-dimensional graphics are supported by the pillow. The objects can be easily annotated or drawn in an image.

Let’s discuss the distinct drawings that can be added to the image:

Drawing Line: Image.Draw.Draw.Line () is the function for joining the coordinates. On the xy plane, one can draw a line by joining the points.

Given below is the syntax that can be used for drawing a line:

   imageDraw.Draw.line (xy,fill=None)

Using the pillow library, here is the code that can be used for drawing a line:

import random 
from PIL import ImagrDraw, Image
def line (image_path, output_path):
image =image.open (image_path)
draw = ImageDraw.Draw (image)
Colors = [“green” , “red” , “yellow”, “blue”, “purple”, “orange”]
for i in range (100, 200, 30):
draw.line ((i,0) + image.size, width = 6, 
fill =random.choice (colors))
image.save (output_path)
if_name_==”_main_”:
line (“madison_bridge_1.png”, “lines.png”)

Input:

input after appliying line

Output – After applying a line to an image

Output after applying line

Drawing Rectangle: Image.Draw.Draw.Rectangle () is the operational function for drawing a rectangle. Below is the syntax that can be used for creating a rectangle:

   ImageDraw.Draw.rectange (xy, fill=None) 

Here, is the code for drawing a rectangle leveraging the Pillow library:

draw_rectangle.py
from PIL import ImageDraw, Image
def rectangle (output_path):
image = image.new (“RGB”, (500, 500), “blue”)
draw =ImageDraw.Draw (image)
draw.rectangle ((100, 200, 300, 400), fill =”red”, 
draw.rectangle ((60, 60, 100, 100), fill=”green”’,
outline =”yellow”,
width = 4
image.save (output_path)
if_name_==”_main_”:
rectangle (“rectangle.jpg”)

Drawing Polygon: Image.Draw.Draw.Polygon () is the operational function used for creating a polygon. The shape of a polygon can be drawn by joining the coordinates through a straight line.

draw_polygon.py
from PIL import ImageDraw, Image
def polygon (output_path):
image = image.new (“RGB”, (500, 500), “grey”)
draw =ImageDraw.Draw (image)
draw.polygon (((50,50),(100,200), (150, 150)), fill =”blue”, 
draw.polygon (((170,200), (200, 100), (100, 50)), 
outline =”black”,
image.save (output_path)
if_name_==”_main_”:
Polygon (“polygons.png”)

Compositing: For overlaying two semi-transparent images, the composting method is used. Leveraging different coefficients, through alpha composting distinct alpha channels and color can be easily mixed. In two-dimensional computer graphics, alpha blending is used for putting rasterized elements in the background of an image.

Creating Animations: In animation, three squares are merged into a single white square. With animation, several versions can be created of an image. In these versions, just the location of the squares is varied. Leveraging an empty list called square_animation, you can easily store various images that are generated.

Animations

[image source]

Animations are the best way to make the content appealing and attractive to the user. Animation can visualize the data in a meaningful and better way. Matplotlib.animation and imageio are the main tools for creating animations in Python.

By calling a plot function inside a loop, animations can be created. Figure, axis, and properties are some of the basic and core elements for framing and creating an animated object.

Also, with the usage of a loop, NumPy arrays for green, red, and blue channels can be created. The array having a green layer represents a square at the center of the image. By the code written below, how animation can help in creating images is mentioned:

square_animation[0].save 
(“animation.gif”,save_all=True,append_images=square_animation[1:])

For appending the images this syntax is used: append_images=square.animation [1]

import numpy as np
from PIL import image
square_animation =[]
for offset in range (1, 50, 2):
red =np.zeros ((500, 500))
green = np.zeros ((400, 400))
blue =np.zeros ((300, 300))
red[101 +offset : 301 +offset, 101 + offset : 301 +offset ] =260
green [300:400, 300:400] = 260
blue [299 -offset : 499 -offset, 299 -offset : 499 -offset] =260
red_img =Image.fromarray(red).convert (“L”)
green_img = Image.fromarray ((blue)).convert (“L”)
square_animation.append
image.merge
“RGB”,
(red_img, green_img, blue_img)

Image Thresholding: Thresholding is the process of converting all the pixels into maximum and minimum values. Three numbers digitally represented each pixel in the image. The three numbers stand for red, green, and blue values of color.

Using the image segmentation techniques, the object can be easily removed from the background of an image. The very first step is to crop the image to a smaller one. After cropping the image, the background or object in an image can be removed.

Using the function .point () each pixel is converted into grayscale. The conversion depends upon the threshold value and grayscale value image. The grayscale value can be greater than or smaller than the threshold value. The values greater than 100 are converted into white color and less than 100 are converted into black color. By varying the threshold value, one can change the sensitivity of an image.

from PIL import Image
filename =”xyz.jpg”
with Image.open (filename_xyz) as img_xyz:
img_xyz.load ()
img_xyz =img_xyz.crop (400, 1, 1600, 1200))
img_xyz.show()

There are also techniques like erosion and dilation for improving the quality of an image. Let’s understand how they can be used in upgrading an image:

Erosion: Erosion is the process of removing the white pixels from the boundaries of an image. By using the ImageFilter.MinFilter(3) as an argument, it can be achieved. The process changes the pixels near the boundary to zero values. In this way, the pixels can be removed from the image.

from PIL import ImageFilter 
filename =”xyz.jpg”
with Image.open (filename) as img:
img.load ()
for _in range (3):
img =img.filter (ImageFilter.MinFilter(3))
img.show()

Dilation: Dilation is just the opposite process of erosion. White pixels are added to the boundaries of an image in the process of dilation. By using ImageFilter.MaxFilter(3) as an argument, the neighboring pixels around the boundary are converted into white color.

from PIL import ImageFilter 
filename =”xyz.jpg”
with Image.open (filename) as img:
img.load ()
for _in range (3):
img =img.filter (ImageFilter.MaxFilter(3))
img.show()

Controlling the decoder: While at the time of reading an image file, the function of decoders is to manipulate the image. While creating the thumbnails, the speed of decoding is highly important. Through the draft () methodology, the resultant image may not exactly match the mode and size of the original image. Because of the variation in the quality and size of an image thumbnail method is used.

Image Filters Using Convolution Kernels

Through image convolution using kernels, image processing can be done. A kernel is a matrix. To better understand the convolution process, consider an image of 30 x 30 pixels. The image has a vertical line and a dot.

The line is 4 pixels wide, while the dot is 4×4 pixel square. The kernel can be placed anywhere on the image and the location of the kernel’s central cell is called a reference. The elements represent different aspects of the image and kernel :

= 1/9 [ 1 1 1 ]
[ 1 1 1 ]
[ 1 1 1 ]

  • White Square: The pixels in the image having a value of zero are represented by a white square.
  • Red Square: The pixels having a value of 255 are red squares in an image.
  • Purple Region: In every image, there is a kernel representing a kernel. The kernel is a 3×3 region. Each cell in the kernel has a value of 1/9.

The process of convolution comprises the following steps mentioned below:

  • Locate Kernel: Locate one of the kernels and figure the image pixels that are covered by the kernel’s nine cells.
  • Multiply the kernel and pixel value: The pixel values in an image need to be multiplied by the kernel’s cell. Nine values can be found in nine multiplications.
  • Results of Multiplication: Following the multiplication, all the values can be added together. The result would be the value of the pixel in the new image. The pixel will have the same coordinates as the kernel’s center pixel.
  • Repeat it for all pixels: For every pixel in an image, the same process of locating the kernel, multiplying, and adding the pixels can be repeated. The kernel can be located at distinct locations in an image. The center of the kernel always corresponds to a different image pixel.

As a result, you will always find a blurred version of an image. Many operations, such as edge enhancing, smoothening, increasing sharpness and contrast can be done on an image.

The quality of an image is improved by performing all these operations. The convolution process can be performed using various built-in kernels and functions.

Also Read => How to Increase the Resolution of the Image


Frequently Asked Questions

1. How can we change the size of an image?

We can easily edit the image using Python programming language or image editor. Below is the code written for resizing an image using the Python Pillow library. Using PIL, we can load and resize an image. The aspect ratio of an image may get changed while resizing an image.
Therefore, for maintaining the quality of the image either it needs to be cropped or scaling needs to be done.
from PIL import image
For opening an image
image = image.open (“image.png”)
For setting the new size of an image
new_size (500, 500)
For resizing an image
resized_image = image.resize( new_size)
For saving the resized image
resized_image.save(‘resized_image.png’)

2. How can we add opacity to a text using Python Pillow?

Opacity can be added to a text using the Python Pillow library as shown below through the code written below:
 
from PIL import Image, ImageDraw, ImageFont
image =image.open (“image.jpg”).convert (“RGB”)
txt_placeholder  = Image.new (‘RGB’, image.size, (0, 255, 255, 500))
d.text ((0,0), “This text is transparent”, fill =(15, 15, 30, 30), font =font)
combined =Image.alpha_composite (image, txt)
font =ImageFont.truetype (“example_font.ttf”, 50)
draw_image =Image.Draw.Draw (txt)
combined.save (“Image_with_text.jpg”)

3. How can you double the size of an image using Pillow?

Using the resize () function, the size of an image can be increased or decreased. The height and width arguments need to be passed. Both the arguments are integers and it is a 2-tuple. The resize function does not modify the present image. It returns a new image with the new dimensions.
For example, if the height and width of image is (400,400). To resize the dimensions needs to be changed. The arguments for the new image should be (800, 800). After passing the new dimensions, the size of an image can be doubled.

4. Using Python how can the background of an image be removed?

Firstly, the RGB needs to be converted into HSV. Following the conversion, the threshold is applied on the image. Using morphological operations, the artifacts can be removed. After that using floodfill, the background of an image needs to be filled. 

5. How can an image be converted into grayscale using Python Pillow?

For converting an image into grayscale, firstly the image filter and image needs to be imported through a module. After successful importing of the image and modules, by leveraging image.convert () function, the image can be converted into grayscale.
When the conversion is done, then the image can be saved using image.save function().

6. How can an image be displayed using the Python Pillow library?

Firstly the module needs to be imported. After importing the image module, an image variable is created. Through the open () function, the image can be opened. The path of the image file needs to be mentioned for calling the show () function.
By calling the show function, the image is displayed on the respective operating system.

7. How can the memory size of an image be reduced in Python?

To reduce the memory size of an image, the best approach is to lower the image resolution. First, by using the Pillow library, the image file can be opened.
After opening the file, the image data can be copied to a new file by passing a low-resolution filter.
By applying this filter, the quality of an image is degraded. This automatically results in a lower-quality picture with a smaller size.


Conclusion

In this write-up, almost all the basic operations of the Pillow library are covered along with the most popular methodologies for leveraging the Pillow library. For more advanced image processing techniques, such as computer vision applications and machine learning, Python Pillow is the stepping stone.

There are many other Python-supporting libraries, such as OpenCV and Scikit Image. Both these libraries support highly advanced functionalities for image processing and are more powerful than Python Pillow. Pillow is also considered for high-level image processing tasks, as it does not require advanced image processing expertise.

The Python community developers use the Pillow library worldwide. Pillow Library is easy to learn and does not require too much effort to learn. Pillow library provides the same functionality and features as the Photoshop software tool.

Further Reading =>> Python Tutorial Series for beginners with hands-on Video Tutorials

Was this helpful?

Thanks for your feedback!

Leave a Comment