What are some basic functions of Image Processing using PIL?

What is Image Processing?

Digital Image Processing is the use of a digital computer to process digital images through an algorithm.

Image processing mainly includes the following steps:

  • Importing the image via image acquisition tools.
  • Analysing and manipulating the image.
  • Output can be an altered image or a report based on that image.

Python Imaging Library (PIL)

PIL is an additional, free, open-source library for the Python programming language that provides support for opening, manipulating, and saving many different image file formats.

# To import PIL
from PIL import Image, ImageFilter

Operations on images using PIL library

1. To open an image and display from a local path:

# To import PIL
from PIL import Image, ImageFilter
# opening the image stored in the local path.
img = Image.open("dog.jpg")
img.show()

2. To know the basic properties of an image:

# To import PIL
from PIL import Image, ImageFilter
# opening the image stored in the local path.
img = Image.open("dog.jpg")
# basic image properties.
print (img.size)
print (img.width)
print (img.height)

3. To rotate an image by a specified angle:

# To import PIL
from PIL import Image, ImageFilter
# opening the image stored in the local path.
img = Image.open("dog.jpg")
# rotating the image with specified angle i.e 45 anticlock wise
rotated_img = img.rotate(45)
rotated_img.show()

Enter the input below

4. To crop an image:

# To import PIL
from PIL import Image, ImageFilter
# opening the image stored in the local path.
img = Image.open("dog.jpg")
# croping the image with the specified boundaries.
cropped_img = img.crop((20,20,500,500)) # left, upper, right, lower
cropped_img.show()

Enter the input below

5. To blur an image:

# To import PIL
from PIL import Image, ImageFilter
# opening the image stored in the local path.
img = Image.open("dog.jpg")
# blur the image.
filtered_img = img.filter(filter = ImageFilter.BLUR)
filtered_img.show()

Enter the input below

6. To resize an image:

# To import PIL
from PIL import Image, ImageFilter
# opening the image stored in the local path.
img = Image.open("dog.jpg")
# resizing the image.
sImg = img.resize((300,200))
sImg.show()

Enter the input below

7. To split the image into R, G, and B formats and merge them:

Getting back the original image by merging all three(R, G, and B) image splits.

# To import PIL
from PIL import Image, ImageFilter
# opening the image stored in the local path.
img = Image.open("dog.jpg")
# split the rgb images into r, g, b individual images and merging again.
r,g,b = img.split()
r.show()
g.show()
b.show()
# merging
im = Image.merge("RGB", (r, g, b))
im.show()

Enter the input below

Image processing is a method used to perform operations on an image to get an enhanced image or to extract some useful information.

Free Resources