Python OpenCV: Resizing an image

In this tutorial we are going to learn how to resize an image using Python and OpenCV.

Introduction

In this tutorial we are going to learn how to resize an image using Python and OpenCV.

This tutorial was tested with version 3.7.2 of Python and with version 4.1.2 of OpenCV.

The code

We will start the code by importing the cv2 module, so we have access to the functions we need to read and resize the image.

import cv2 

Then we will take care of reading the image with a call to the imread function. As input, we need to pass the path to the image in the file system, as a string.

img = cv2.imread('C:/Users/N/Desktop/test.jpg') 

To resize an image with OpenCV, we simply need to call the resize function. This function has some optional parameters, but the mandatory ones are the image to be resized and the desired output size (specified as a tuple).

Note that the first element of the tuple is the new width and the second element the new height.

resized = cv2.resize(img, (200,200))

There’s another approach that we can follow to resize the image, by using some of the optional parameters of the resize function.

More specifically, we are going to specify a scale factor for both the x and the y axis. The optional parameters that allow to do it are called fx and fy, respectively. These parameters can be specified as floats.

When we follow this approach, we should set the previously used tuple resize parameter to None. For testing purposes, we are going to scale both x and y axis by a factor of 2.0.

resized2 = cv2.resize(img, None, fx = 2.0, fy = 2.0)

To finalize, we will display both images in two different windows.

cv2.imshow('Resized img 1', resized)
cv2.imshow('Resized img 2', resized2)

cv2.waitKey(0)
cv2.destroyAllWindows()

The final code can be seen below.

import cv2 

img = cv2.imread('C:/Users/N/Desktop/test.jpg') 

resized = cv2.resize(img, (200,200))
resized2 = cv2.resize(img, None, fx = 2.0, fy = 2.0)


cv2.imshow('Resized img 1', resized)
cv2.imshow('Resized img 2', resized2)

cv2.waitKey(0)
cv2.destroyAllWindows()

Testing the code

To test the code, simply run it using a tool of your choice. I’ve used IDLE, a Python IDE.

You should get a result similar to figure 1. As can be seen, the first image was resized to the specified size (200×200), which is smaller that the original image. The second image was resized by a factor of 2.0 in both axis, which means it is bigger than the original image.

Output of the program, showing both resized images
Figure 1 – Output of the program, showing both resized images.

Leave a Reply

%d bloggers like this: