Computer vision is a fascinating field that enables machines to interpret and process visual information, allowing them to perform complex tasks like object detection, image recognition, and much more. In this blog, we’ll learn a crucial application of computer vision, which is image resizing.
Image resizing refers to scaling the dimensions of an image by updating the width or the height. This is done by changing the pixels of an image.
An image can either be upscaled or downscaled.
Upscaling refers to increasing the number of pixels within the image by interpolating new pixels. The size of an image increases, but the quality of pixels is affected.
Downscaling refers to decreasing the number of pixels within the image. The size of an image decreases.
The aspect ratio refers to the ratio of the width and height of a particular image. The resized image can have the same ratio of width and height as the original image or a different ratio of width and height from the original image. Not preserving the aspect ratio leads to distorted images. We’ll see the effects of the actions mentioned above in the upcoming output sections.
In Python, image resizing can be performed using various methods. Python itself offers a method called resize()
. A library called Pillow can also be used for this task. However, OpenCV provides a highly efficient way to perform image resizing with various customization options. The focus of this blog will be to apply OpenCV’s methods for image resizing in Python.
OpenCV is a highly efficient open-source computer vision and machine learning library. We can process images and videos, handle real-time computer vision tasks, perform feature detection, object recognition, and many other computer vision tasks using this library.
To ensure that OpenCV code can seamlessly run in your Python environment, ensure that the opencv
library is installed.
First, upgrade pip
if it isn’t up to date already. This can be done by running the following command:
pip install --upgrade pip
Next, install the `opencv` library using the following command:
pip install opencv-python
resize(InputArray src, OutputArray dst, Size size, double fx, double fy, int interpolation)
The resize()
method takes the following parameters:
src
is the input image.
dst
is the output image.
dsize
is the size of the output image.
fx
is the horizontal scaling factor.
fy
is the vertical scaling factor.
The interpolation method is the way to calculate new image pixels. The following table briefly discusses the possible options for interpolation methods offered by OpenCV.
Interpolation method | Explanation |
| Default value: resampling through bilinear interpolation |
| Resampling through nearest neighbor interpolation |
| Resampling through pixel area relation |
| Bicubic interpolation over a 4 x 4 pixel neighborhood |
| Lanczos interpolation over a 8 x 8 pixel neighborhood |
The cv2.INTER_AREA
method is generally used when reducing the size of an image. The cv2.INTER_CUBIC
and cv2.INTER_LINEAR
methods are used for increasing the size of an image. The cv2.INTER_CUBIC
method takes more processing time as compared to cv2.INTER_LINEAR
but also generates higher quality results.
Note: Either
dsize
orfx / fy
should have a nonzero value.
OpenCV allows us to perform resizing using two ways, either through scaling or by using specific values for the width and height.
The first way to use the resize()
method is to give it a single scaling factor that either increases or decreases the size of the image. Using the resize()
method with a scaling factor provides surety that the aspect ratio will not be altered. The width and height maintain their ratio and are scaled up or down accordingly.
The second way to use the resize()
method is to give it both the width and height of the new image. The new width and height can either:
Have the same ratio as before (if you calculate it yourself).
Have a different ratio from the original one.
The second point can cause unintended distortion. This distortion can cause the image to become stretched or squashed. Unless there is a specific need for it, the proportionality of the width and height should be maintained.
Let’s take a look at two coding examples that demonstrate increasing and decreasing the size of an image using OpenCV.
The following code reduces the size of an image using a scaling factor of 0.5
across both axes.
import cv2import matplotlib.pyplot as pltdef load_image(img_path):return cv2.imread(img_path)def resize_image(original_image, scaling_factor_x, scaling_factor_y):x = scaling_factor_xy = scaling_factor_yresized_image = cv2.resize(original_image, (0,0), fx=x, fy=y, interpolation=cv2.INTER_AREA)return resized_imageoriginal_img = load_image("orig_img.jpeg")scaling_factor_x = 0.5scaling_factor_y = 0.5new_image = resize_image(original_img, scaling_factor_x, scaling_factor_y)fig, axes = plt.subplots(1, 2, figsize=(12, 6))axes[0].imshow(cv2.cvtColor(original_img, cv2.COLOR_BGR2RGB))axes[0].set_title("Original image")axes[0].axis("on")axes[0].set_xlim([0, 800])axes[0].set_ylim([400, 0])axes[1].imshow(cv2.cvtColor(new_image, cv2.COLOR_BGR2RGB))axes[1].set_title('Resized image')axes[1].axis('on')axes[1].set_xlim([0, 800])axes[1].set_ylim([400, 0])plt.show()
Output: The following image depicts the output of the code. We can see that the image size has been decreased by a scaling factor of 0.5
.
Similarly, the following code increases the size of an image using a scaling factor of 2
across both axes.
import cv2import matplotlib.pyplot as pltdef load_image(img_path):return cv2.imread(img_path)def resize_image(original_image, scaling_factor_x, scaling_factor_y):x = scaling_factor_xy = scaling_factor_yresized_image = cv2.resize(original_image, (0,0), fx=x, fy=y, interpolation=cv2.INTER_CUBIC)return resized_imageoriginal_img = load_image("orig_img.jpeg")scaling_factor_x = 2scaling_factor_y = 2new_image = resize_image(original_img, scaling_factor_x, scaling_factor_y)fig, axes = plt.subplots(1, 2, figsize=(12, 6))axes[0].imshow(cv2.cvtColor(original_img, cv2.COLOR_BGR2RGB))axes[0].set_title("Original image")axes[0].axis("on")axes[0].set_xlim([0, 1600])axes[0].set_ylim([800, 0])axes[1].imshow(cv2.cvtColor(new_image, cv2.COLOR_BGR2RGB))axes[1].set_title('Resized image')axes[1].axis('on')axes[1].set_xlim([0, 1600])axes[1].set_ylim([800, 0])plt.show()
Output: The following image depicts the output of the code. We can see that the image size has been increased by a scaling factor of 2
.
A general explanation for the code snippet is given below:
Lines 1–2: First, we import the necessary libraries.
cv2
: This represents the OpenCV library for computer vision tasks.
matplotlib.pyplot as plt
: This refers to the Matplotlib library for plotting tasks.
Lines 4–5: We define a load_image
function to load an image using OpenCV’s built-in imread
method.
Lines 7–11: We define a resize_image
function to resize an image using OpenCV’s `resize` method with our specified scaling factors.
Line 13: We load the original image using the load_image("orig_img.jpeg")
function.
Lines 15–18: We specify scaling factors for the x and y axis using scaling_factor_x
and scaling_factor_y
, respectively, and resize the original image using the resize_image
function.
Lines 20: For plotting the result, we create a subplot with two columns using fig, axes = plt.subplots(1, 2, figsize=(12, 6))
.
Lines 22–26: Matplotlib is used to display the original image on the left subplot by:
Converting the color space from BGR to RGB using the cv2.cvtColor
function.
Setting the title, turning on the axes, and setting axes limits.
Lines 28–32: Matplotlib is used to display the resized image on the right subplot by:
Converting the color space from BGR to RGB using the cv2.cvtColor
function.
Setting the title, turning on the axes, and setting axes limits.
We show the final plot using the matplotlib show()
function.
Note: Remember to replace
orig_img.jpeg
with the path of the image that you want to resize.
There are numerous domains and applications for image resizing, including but not limited to the following:
Machine learning
Image processing
Medical imaging
Graphic designing
Web development
Congratulations, you have successfully learned to resize images using OpenCV in Python. This is your cue to go and master computer vision in Python with OpenCV and become an OpenCV expert in no time. If you want to learn OpenCV in another language, you can learn OpenCV in C++ from scratch. Happy coding!
Free Resources