How to Resize an Image using cv2.resize() method: 3 Steps Only

Do you want to resize an image in python using cv2. Then you have come to the right place. In this entire tutorial, you will know how to scale and resize an image using the OpenCV cv2 resize() method with step by step.

Steps to Implement cv2 reize() method in python

Step 1: Import all the necessary libraries

The first and basic step is to import all the necessary libraries. In our example, I am using the OpenCV module and the matplotlib python module. The matplotlib module will be used for displaying the image. Please note that I am executing all examples in the Jupyter notebook. Make sure that you also do all the work on it for a better understanding. Let’s import all the modules.

import cv2
import matplotlib.pyplot as plt
%matplotlib inline

The statement %matplotlib inline allows you to display all the images in inline.

Step 2: Read the image

Now before resizing the image you have to read the image.  There is a method in OpenCV for it and that is the cv2.imread() method.

# read image
img = cv2.imread("owl.jpg")
plt.imshow(img)

Output

Sample image for implementing cv2 resize

Step 3: Resize the image using cv2.resize() method

After reading the image in step 2, in this section, I will resize the image using the resize() method. If you print the shape of the original image then you will get a width of 1280 and a height of 960.

# shape of image
print(img.shape)

Output

(960, 1280, 3)

Suppose I want to resize the image to 500×600 pixels. Then I will pass these dimensions inside the resize() method.

# resize the image
resized_img = cv2.resize(img,(500,600))
plt.imshow(resized_img)

Output

Resized Image of 600×500 dimension

If you print the shape of the image then you will get the output as below.

print(resized_img.shape)

Output

(96, 128, 3)

If you look at the above-resized image, then you will see the image is not look good after the resizing. How to properly resize it. To do so you have to scale the image. Scaling allows you to adjust the image proportionally so that it looks good.

Run the code given below.

scale = 0.1
width = int(img.shape[1]*scale)
height = int(img.shape[0]*scale)
resized_img_with_scaling = cv2.resize(img,(width,height))
plt.imshow(resized_img_with_scaling)

Output

Resized and Scaled Image

You can verify the size of the image using the resized_img_with_scaling.shape.

print(resized_img_with_scaling.shape)

Output

(96, 128, 3)

Conclusion

There are also other python modules that allow you to resize an image. But I will prefer you to use cv2.resize() method for it. These are the steps to resize any image. Hope you have liked this “how-to” tutorial. If you have any other queries then you can contact us for getting more help.

Source

OpenCV Documentation