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)
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)
(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)
If you print the shape of the image then you will get the output as below.
(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*scale) height = int(img.shape*scale) resized_img_with_scaling = cv2.resize(img,(width,height)) plt.imshow(resized_img_with_scaling)
You can verify the size of the image using the resized_img_with_scaling.shape.
(96, 128, 3)
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.
Join our list
Subscribe to our mailing list and get interesting stuff and updates to your email inbox.