Image Manipulation with Python

Posted on March 12, 2021July 7, 2022

First, we need to know what we mean by the above title. So, let’s explore.

What are some Python image manipulation use cases?

So, Python is considered as the Swiss knife of programming languages, as we can do so many things with it. One of them is manipulating images. Image manipulation can include changing resolution, resizing, changing contrast, saturation, file extensions, color channels, and many more.

Python Image Manipulation Modules

Python has multiple image manipulation modules. So, for the scope of this blog, let’s discuss Pillow and OpenCV first.

Pillow and OpenCV

So, Pillow is part of Python’s PIL (Python Imaging Library), it’s as simple as an image manipulation module can be. The functions are simple and a very high level of editing can’t be done with it.

On the other hand, the functions in OpenCV are much more complicated and versatile, you can add masks, extract backgrounds, use bitwise operation on image pixels, and do operations on different colour channels.

Out of those two modules, we are going to use Pillow for this blog to get started. We can move onto the more complicated module, OpenCV, in a future blog.

But the installation and import procedure for OpenCV has still been mentioned.


For Windows users:

Simply open your ‘cmd’ and type:

For Pillow:

`pip install pillow`

For OpenCV:

`pip install opencv-python `

For Linux users:

For Pillow:

`pip3 install pillow `

For OpenCV:

`pip3 install opencv-python`

To Import Simply

from PIL import Image #for pillow

import cv2 as cv #for opencv


Going forward, we are going to see the code for the operations, and we might want to perform on below sample images, separated by modules-first Pillow, and then OpenCV.

Referred to as cat.jpg and mountain.jpg

4K5V1m1zqTIWVFjzQ6ACy77U0KdZagZpAZC4vnrLAdLZskg3X73MpPTAecSSDVEl LzkZ8hejiSy6dWbvAF2QoKVb56D2wUj10JlGFLzwGrfc7WKE4qS KL26eth319yACz1zFD6UneQGONCRAQt2D0zzZQhrVPcikB5scYmqH4ACItd4uTtCuUOoy78Mz3GtHInH3oF aaB1GTuPbA8rDbno4syG7xN2FHtqUkTtyz3JrH9gbTSMwkJxjLAgSE2H26y01W3A6uF5Zzj 2BJz6XYSOhAOSb fQ9g


Now just a small disclaimer, Pillow has hundreds of functions, and you might need to use many of them, but this blog will only give you an idea on the basic functions and just the feel of the syntax overall. 

Any kind of operation you think is possible, you just need to go and search for it.

Let’s hope the function you are looking for is present in this blog, but even if it’s not, you can head over to the pillow documentation here :- or

Open Image

from PIL import Image

# just opening an image by it’s path

# if image is in the same folder

# we can just write its name 

img1 =‘cat.jpg’)

img2 =‘mountain.jpg’)

# we can use the img object we created to perform operations

# we can also save the image using a different name or extension‘kitty.png’)
yqHuge8W PXLUkLbWcvYrUfzEX1PJBidXUTPi8RWJ0DSNh5CVi5SF5LASoWGuX4UEBGWQX kcqmki1MK45gndpl2soClWS jchnuy3gKFfds9p7hIQ9qth kvQHVpMkkW0cQbDxYtERiW VqQQ

This will simply show the image in your default image viewer.

Resize Images

Change Resolution

from PIL import Image

i =“cat.jpg”)

print(i.size) # printing out original width and height

i_new = i.resize((200,100)) # resizing to new (width, height)



F9hrXYxyzE xtWmlwAyraU1Vozg9R8JIhWMMSzZaeaaA10RvAialmb0XB6iIzqTmu29CHlK3CC kNRCsP10Cy m6CWfL jXwaLUBIiAAyKx BnR2V3k9OHE3NVtGntrr6x39TEoV8YG kXhCrg

We see the original image, the resized image and their shapes as output.

BENMSyMDEofps0Of4P yWtZctQP 2gz2Ff4AHZClBuuoaOgcpnIuwE2XQ2imBe2Wxr48YImxnuoD71qJgpk8t47Kn4FQT3W CRLNxPj4wNVQrTj9WIVuAprvbumAX

Crop Image

from PIL import Image

img =‘./cat.jpg’)

# top left of image is 0,0 and we are selecting the x,y coordinates of the top left and bottom right corner of the crop respectively

img = img.crop((200, 200, 300, 300))

So, the crop method takes 4 inputs, which are x1,y1,x2,y2 respectively, and x2 and y2 shouldn’t be more than the size of the image itself.

HFdmlC aMYAmZb2bPpIIc wOalLceL1BQjiTvGI8roi3TguO 1aWLT0QuxNvG96xgvjBjFWqiqPSUclOopRZqtOOgKa1voD0dU0PIouC9oq

Move Images

Rotate Image

from PIL import Image

i =“mountain.jpg”)

i = i.rotate(90) # inputs in degrees

# saving rotated image“mountain_rotated.jpg”)
0s X1PsX5kc2qB97HjfG1iefpcmS1IbGE Qlp4wKDPfAcOAH68I aQP MDUpIEkToheU5zaA2JK02I7oW4Bmt1hJY4nWXxcsbQi510uaNYJwS

Shift Image

from PIL import Image, ImageChops

img =“cat.jpg”)

# first we pass the image then the x axis shift and then the y axis shift respectively

img = ImageChops.offset(img, -200, 100)“cat_offset.jpg”)

Flip Image

from PIL import Image, ImageOps

i =“cat.jpg”)

i_flip = ImageOps.flip(i)

# saving flipped(vertically) image“cat_flipped.jpg”)

i_mir = ImageOps.mirror(i)

# saving mirrored(horizontally) image“cat_mirrored.jpg”)

Below are the mirrored and flipped outputs, respectively. Keep in mind this doesn’t affect the resolution whatsoever.

Edit Images

qBvRJrct6d9AOiSChirKJ3vp3gSk wv H buVDZt458b57plSgW7ozy58kcrfojfp6t9dqAfMl tXF o9TWvf0uo3vG2aSKolTRFT4G6VlKzqb1NGs6K qB6oBFX ZGV BZEjPZUerTtYVva5g

Blur Image

from PIL import Image, ImageFilter

i =“cat.jpg”)

# there are different types of filters available the number inside the Gaussian Blur decides the strength of the blur

i_blur = i.filter(ImageFilter.GaussianBlur(6))“cat_blur.jpg”)

Black and White Image

from PIL import Image, ImageFilter

i =“cat.jpg”)

# here changing the mode changes the output image colour mode

i_bw = i.convert(mode=’L’)“cat_bw.jpg”)

# this mode kind of pixelates the lines/edges

i_grain = i.convert(mode=’1′)“cat_grain.jpg”)

Keep in mind these conversions are mostly mutual. You can mix and match all these conversions.

For example, you can have a blurred, black and white cat image crop .54ViVyyM oUGewRC9Os 1mVJPOZO2yw8yAPnCCcVrmh JTwr1XuqBkKI8lH20YxlR6ss19pF8eVoACuK 7f zqK39vyYbCHpDFSTBFXpbgI1n5HDdWZfZ0ngdTXldKBoPI3JfBBg VG9Hn Kdw

You can also have a mirrored, grainey resized, and rotated image.

Multiple Operations Example

One thing to keep in mind is that based on the sequence of the operation, the output image can be the same even when the operations are performed in a different order on the same image, or it can be different, depending on the operation types, the sequence and the image.
R N2utFZrnh9x poBwmUlBbUCSbYeXm

from PIL import Image, ImageFilter, ImageOps

img =‘./cat.jpg’)

# cropping the body area of the cat

img = img.crop((200, 125, 420, 310))

# Blurring the image

img = img.filter(ImageFilter.GaussianBlur(6))

# then mirroring the image

img = ImageOps.mirror(img)

# and converting the image into black and white in the end

img = img.convert(mode=’L’)

Mass Operations Example

Now you might have realised that the operations we performed can be done even in an image editing app, even though this is faster as we only need to write a couple of lines of code.

But coding the image edits has a significant advantage in a scenario, when we have hundreds of images.

We can integrate the Pillow module functions with the Python syntax and apply logic, and we can use if else conditions or for loops, so filter out images based on name and then perform operations based on that.

Using loops, we can perform operations on hundreds, even tens of thousands of images with simple lines of code, which is impractical if we open images one by one in an application.

So let’s take this huge dataset, for example : 

Now here, the resolutions and names are different and not at all organised, so we will use Pillow to resize and rename all these images one by one:

from PIL import Image

import os # we need os to list out the files in the dataset folder

# let’s take the training dataset for now and we can repeat the process for the test dataset by just changing the root

root = “./gender_dataset/train”

# here we are storing the different folder names in a list

folders = os.listdir(root)


# now we are iterating on the folders

for folder in folders:

   # now for every folder we are listing out all the files(images) inside that folder

   files = os.listdir(root+folder)


   x = 0

   for file in files:

  # any if condition can be used here based on the file name eg.

  # if “.png” in file:

  #    continue

       # this number will be used for new image names


  # now we open the images

       i = + folder + “/”+ file)

  # here we resize all the images to 1 resolution

       i = i.resize((96,64))

  # and save the images with new name in a different folder with same name“./gender_resized/train/”+folder+”/”+str(x)+”.jpg”)

       # just printing out the name of the image so know our progress


Output Folder:

Just the first few images

PMfen36ifRcpPWlgdBRbGzyp6TiUjRWbrTcg40VeQ96Yua7bvo35dLZ0aIb21GIPlpR64EuQ3860h5RLCWWM inyEjvNRvxDSLm4O6tDgtgrhK4Cl2 OqUKnFtYGF2BrUXPhD q3YkeRdYon6Q


Now, we hope you’ve learned about how one can use Python modules for image manipulation. Simple as it may be, Pillow is still much better and faster when you want to perform basic operations on a huge number of images.

Many more advanced image operations are left and will be continued in the next part of this blog, in which we will use OpenCV to perform image manipulation. 

Simple as it may be, Pillow is still much better and faster when you want to perform basic operations on a huge number of images. If you enjoyed reading this blog, you can also read this blog-’’Image Classification with Python.’’

Similar Posts

logo think create apply new 2 2048x525 1
Group 271
Group 545 4
Group 270

Launching New
3D Unity Course