Resize all images of a directory to a specific size in Python

In this tutorial, I will tell you how you can resize all images of a directory to a specific size.

Hello friends, in our tutorial on resize image in Python you learned how to resize an image.

We will cover two modules in this tutorial :

Resize images of a directory to a specific size using Pillow

I have a directory named 'images'. It consists of 10 images with different dimensions.

Dimensions of all the 10 images : 

(2121, 1414)
(586, 586)
(275, 183)
(275, 183)
(183, 275)
(292, 173)
(1280, 720)
(1100, 1329)
(3000, 2000)
(301, 167)

Now, I wish to resize these images to a specific dimension of 150×150. At first, I imported two modules, os and PIL. Store your directory’s path in a temporary variable. Here, file variable holds the path to my directory. Now I have run a for loop which iterates the list of all the files in the directory. To get a list of all the contents of my directory, I have used the listdir() function and passed my directory’s path as an argument. Now, I have added every iterated image’s path to the original path and stored it in the variable img_path.

Code :

import os
from PIL import Image

file = r'/C:/Desktop/images'
for image in os.listdir(file):
    img_path = file + "/" + image
    img = Image.open(img_path)
    img = img.resize((150, 150))
    img.save(img_path)

Using the Image function of PIL module, I have opened the particular image. Once opened you can resize the image using the resize() function. I have passed my desired dimension as an argument to the latter. Make sure to save this resized image by using the save attribute and specifying, the location.

Output : 

Dimension of all 10 images after resizing :

(150, 150)
(150, 150)
(150, 150)
(150, 150)
(150, 150)
(150, 150)
(150, 150)
(150, 150)
(150, 150)
(150, 150)

Resize images of a directory to a specific size using cv2

You can also resize the images using cv2 module. You can check our tutorial on OpenCV Python and learn the basics of cv2. I have also ran a for loop here to iterate over the contents of the directory and added the image’s path to the original path. imread() function is used to read the image. I have used the resize() function to resize the dimension. Pass the read image and the dimensions to the function. I have stored this resized image in a temporary variable, img_resize. Now, to save this image, I have used imwrite() function and passed the variable img_resize and the location.

Code :

import os
import cv2

file = r'/C:/Desktop/images'
for image in os.listdir(file):
    img_path = file + "/" + image
    img = cv2.imread(img_path)
    img_resize = cv2.resize(img, (150,150))
    cv2.imwrite(img_path, img_resize)

Using these modules, you can resize all the images of a directory to a specific size.

Leave a Reply

Your email address will not be published. Required fields are marked *