fbpx
Subscribe for More
Subscribe for More
Edit Content
Click on the Edit Content button to edit/add the content.

Image Resizing with OpenCV

Come, let’s learn about image resizing with OpenCV. To resize an image, scale it along each axis (height and width), considering the specified scale factors or just set the desired height and width.  

When resizing an image:

  • It is important to keep in mind the original aspect ratio of the image (i.e. width by height), if you want to maintain the same in the resized image too.
  • Reducing the size of an image will require resampling of the pixels. 
  • Increasing the size of an image requires reconstruction of the image. This means you need to interpolate new pixels.

Various interpolation techniques come into play to accomplish these operations. Several methods are available in OpenCV, the choice typically depends on the particular application.

Let’s go through the code example for making an image larger and smaller by resizing with custom height and width. As you proceed further, we will discuss resizing with different scale factors and interpolation methods as well.

Python

# let's start with the Imports 
import cv2
import numpy as np

# Read the image using imread function
image = cv2.imread('image.jpg')
cv2.imshow('Original Image', image)

# let's downscale the image using new  width and height
down_width = 300
down_height = 200
down_points = (down_width, down_height)
resized_down = cv2.resize(image, down_points, interpolation= cv2.INTER_LINEAR)

# let's upscale the image using new  width and height
up_width = 600
up_height = 400
up_points = (up_width, up_height)
resized_up = cv2.resize(image, up_points, interpolation= cv2.INTER_LINEAR)

# Display images
cv2.imshow('Resized Down by defining height and width', resized_down)
cv2.waitKey()
cv2.imshow('Resized Up image by defining height and width', resized_up)
cv2.waitKey()

#press any key to close the windows
cv2.destroyAllWindows()

C++

// let's start with including libraries 
#include<opencv2/opencv.hpp>
#include<iostream>

// Namespace to nullify use of cv::function(); syntax
using namespace std;
using namespace cv;

int main()
{
	// Read the image using imread function
	Mat image = imread("image.jpg");
	imshow("Original Image", image);


	// let's downscale the image using new  width and height
	int down_width = 300;
	int down_height = 200;
	Mat resized_down;
	//resize down
	resize(image, resized_down, Size(down_width, down_height), INTER_LINEAR);
	// let's upscale the image using new  width and height
	int up_width = 600;
	int up_height = 400;
	Mat resized_up;
	//resize up
	resize(image, resized_up, Size(up_width, up_height), INTER_LINEAR);
	// Display Images and press any key to continue
	imshow("Resized Down by defining height and width", resized_down);
	waitKey();
	imshow("Resized Up image by defining height and width", resized_up);
	waitKey();


	destroyAllWindows();
	return 0;
}

Master Generative AI for CV

Get expert guidance, insider tips & tricks. Create stunning images, learn to fine tune diffusion models, advanced Image editing techniques like In-Painting, Instruct Pix2Pix and many more

We assume you already have OpenCV in your system. If you need to install OpenCV, please visit the relevant link below.
  1. Install OpenCV on Windows
  2. Install OpenCV on MacOS
  3. Install OpenCV on Ubuntu

Read The Image

Let’s begin by importing the required modules as shown below.

Python

# Importing the libraries  
import cv2
import numpy as np
Download Code To easily follow along this tutorial, please download code by clicking on the button below. It's FREE!

C++

#include<opencv2/opencv.hpp>
#include<iostream>
// Namespace to nullify use of cv::function(); syntax
using namespace std;
using namespace cv;

Next, read in a test image, using the imread() function, as discussed in previous posts. The syntax is shown below.

Image with Bugatti Veyron car, in Black and Red colors. This same image would be used throughout the article.
Input image of car we will use throughout this post.

Python

# Reading image
image= cv2.imread('image.jpg')

C++

// Reading image
   Mat image = imread("image.jpg");

Note that in the C++ snippet, you first created a matrix for the image, then used the imread() function to read it.

Before you start resizing the image, know its original size. To obtain the size of an image:

  • use the shape method in Python
  • rows and cols in C++ 

image.shape in Python returns three values: Height, width and number of channels.

In C++:

  • image.rows gives you the height
  • image.columns gives you the width of the image 

The above results can also be obtained, using the size() function. 

  • image.size().width returns the width
  • image.size().height returns the height

Python

# Get original height and width
h,w,c = image.shape
print("Original Height and Width:", h,"x", w)

C++

// Get height and width
cout << "Original Height and Width :" << image.rows << "x" << image.cols << endl;

One important thing to note here is that OpenCV outputs the shape of an image in height * width * channels format, whereas some other image-processing libraries give in the form of width, height. There’s a logical take to this.

When images are read using OpenCV, they are represented as NumPy arrays. And in general, you always refer to the shape of an array, in terms of rows * columns (rows representing its height and the columns its width). So, even when reading images with OpenCV to get their shape,  the same NumPy array rule comes into play. And  you get the shape in the form of height * width * channels.

Resize Function Syntax

Let’s begin by taking a look at the OpenCV resize() function syntax. Notice that only two  input arguments are required: 

  1. The source image.
  2. The desired size of the resized image, dsize.

We will discuss the various input argument options in the sections below.

resize(src, dsize[, dst[, fx[, fy[, interpolation]]]])

  • src: It is the required input image, it could be a string with the path of the input image (eg: ‘test_image.png’).
  • dsize: It is the desired size of the output image, it can be a new height and width.
  • fx: Scale factor along the horizontal axis.
  • fy: Scale factor along the vertical axis.
  • interpolation: It gives us the option of different methods of resizing the image.

Resizing by Specifying Width and Height

In this first example, let’s resize the image by specifying a new width and height that will downscale the image. In the code below:

  • We set the desired width as 300 and the desired height, 200. 
  • These two values are combined in a 2D vector, required by the resize() function. 
  • We also specify the interpolation method, which happens to be the default value.

Python

# Set rows and columns 
# lets downsize the image using new  width and height
down_width = 300
down_height = 200
down_points = (down_width, down_height)
resize_down = cv2.resize(image, down_points, interpolation= cv2.INTER_LINEAR)

C++

// Set rows and columns 
// lets downsize the image using new width and height
   int down_width = 300;
   int down_height = 200;
   Mat resize_down;

   // resize down
   resize(image, resize_down, Size(down_width, down_height), INTER_LINEAR);

Next, we create another variable to increase the size of the image. 

Python

# Set rows and columns
up_width = 600
up_height = 400
up_points = (up_width, up_height)
# resize the image
resized_up = cv2.resize(image, up_points, interpolation = cv2.INTER_LINEAR)

C++

// Set rows and columns
int up_width = 600;
int up_height = 400;
Mat resized_up;
//resize up
resize(image, resized_up, Size(up_width, up_height), INTER_LINEAR);

In the above Python snippet, we are defining new width and height to upscale the image, using the resize() function. Process and steps are similar to the previous snippet.

In the C++ snippet:

  • We define new integers for width and height for upscaling.
  • Give a matrix for the output image.
  • Then use the resize() function, same as the previous snippet.

Now, let us display all the images using the imshow() function from OpenCV.

Python

# Display images
cv2.imshow('Resized Down by defining height and width', resized_down)
cv2.waitKey()
cv2.imshow('Resized Up image by defining height and width', resized_up)
cv2.waitKey()
cv2.destroyAllWindows()

C++

// Display Images and press any key to continue
imshow("Resized Down by defining height and width", resized_down);
waitKey();
imshow("Resized Up image by defining height and width", resized_up);
waitKey();
destroyAllWindows();
Figure showing resized down and resized up images.
The left image shows the resized down image and the right one the resized up image.

Our resize operations worked as expected. The image either got bigger or smaller, according to the new height and width parameters we defined. But one thing to note is that such resizing by defining an explicit value for width and height is making the resulting image distorted. That is, the aspect ratio of the image does not stay intact.

So, how to correct this? Well, you’ll have to learn to use a scaling factor when resizing.

Resizing With a Scaling Factor

Okay, so now we resize the image with a scaling factor. But before going further, you need to understand what exactly is a scaling factor. 

Scaling Factor or Scale Factor is usually a number that scales or multiplies some quantity, in our case the width and height of the image. It helps keep the aspect ratio intact and preserves the display quality. So the image does not appear distorted, while you are upscaling or downscaling it.

Python

# Scaling Up the image 1.2 times by specifying both scaling factors
scale_up_x = 1.2
scale_up_y = 1.2
# Scaling Down the image 0.6 times specifying a single scale factor.
scale_down = 0.6

scaled_f_down = cv2.resize(image, None, fx= scale_down, fy= scale_down, interpolation= cv2.INTER_LINEAR)
scaled_f_up = cv2.resize(image, None, fx= scale_up_x, fy= scale_up_y, interpolation= cv2.INTER_LINEAR)

C++

// Scaling Up the image 1.2 times by specifying both scaling factors
double scale_up_x = 1.2;
double scale_up_y = 1.2;
// Scaling Down the image 0.6 times specifying a single scale factor.
double scale_down = 0.6;
Mat scaled_f_up, scaled_f_down;
//resize 
resize(image,scaled_f_down, Size(), scale_down, scale_down, INTER_LINEAR);
resize(image, scaled_f_up, Size(), scale_up_x, scale_up_y, INTER_LINEAR);

In the above Python snippet:

  • We define new scaling factors along the horizontal and vertical axis. 
  • Defining the scaling factors removes the need to have new points for width and height. Hence, we keep dsize as None. 

In the above C++ snippet:

  • We define the new scaling factors as well as the matrices for the new images.
  • As we do not need new points for width and height, we keep Size() empty and use the resize() function. 

Now, let us display the images for visualization and better understanding.

Python

# Display images and press any key to check next image
cv2.imshow('Resized Down by defining scaling factor', scaled_f_down)
cv2.waitKey()
cv2.imshow('Resized Up image by defining scaling factor', scaled_f_up)
cv2.waitKey()

C++

// Display images and Press any key to continue check next image
imshow("Resized Down by defining scaling factor", scaled_f_down);
waitKey();
imshow("Resized Up by defining scaling factor", scaled_f_up);
waitKey();
A comparative image with Scaled-Down version on left and on right we have the Scaled Up version.
Left image is the scaled down version and on the right is the scaled up version.

Resizing With Different Interpolation Methods

Different interpolation methods are used for different resizing purposes.

  • INTER_AREA: INTER_AREA uses pixel area relation for resampling. This is best suited for reducing the size of an image (shrinking). When used for zooming into the image, it uses the INTER_NEAREST method.
  • INTER_CUBIC: This uses bicubic interpolation for resizing the image. While resizing and interpolating new pixels, this method acts on the 4×4 neighboring pixels of the image. It then takes the weights average of the 16 pixels to create the new interpolated pixel.
  • INTER_LINEAR: This method is somewhat similar to the INTER_CUBIC interpolation. But unlike INTER_CUBIC, this uses 2×2 neighboring pixels to get the weighted average for the interpolated pixel.
  • INTER_NEAREST: The INTER_NEAREST method uses the nearest neighbor concept for interpolation. This is one of the simplest methods, using only one neighboring pixel from the image for interpolation.

Do not worry if you do not understand the interpolation methods completely. We will cover them in a separate post.

Python

# Scaling Down the image 0.6 times using different Interpolation Method
res_inter_nearest = cv2.resize(image, None, fx= scale_down, fy= scale_down, interpolation= cv2.INTER_NEAREST)
res_inter_linear = cv2.resize(image, None, fx= scale_down, fy= scale_down, interpolation= cv2.INTER_LINEAR)
res_inter_area = cv2.resize(image, None, fx= scale_down, fy= scale_down, interpolation= cv2.INTER_AREA)

C++

# Scaling Down the image 0.6 using different Interpolation Method
Mat res_inter_linear, res_inter_nearest, res_inter_area;
resize(image, res_inter_linear, Size(), scale_down, scale_down, INTER_LINEAR);
resize(image, res_inter_nearest, Size(), scale_down, scale_down, INTER_NEAREST);
resize(image, res_inter_area, Size(), scale_down, scale_down, INTER_AREA);

In the above Python snippet, we are resizing the image using different Interpolation methods. Similarly, in the C++ snippet, we are first defining new matrices for output images, then resizing them with different Interpolation methods. Let’s display the images now.

Python

# Concatenate images in horizontal axis for comparison
vertical= np.concatenate((res_inter_nearest, res_inter_linear, res_inter_area), axis = 0)
# Display the image Press any key to continue
cv2.imshow('Inter Nearest :: Inter Linear :: Inter Area', vertical)

C++

Mat a,b,c;
vconcat(res_inter_linear, res_inter_nearest, a);
vconcat(res_inter_area, res_inter_area, b);
vconcat(a, b, c);
// Display the image Press any key to continue
imshow("Inter Linear :: Inter Nearest :: Inter Area :: Inter Area", c);
Figure showing image resizing with different interpolation methods
INTER_LINEAR on the left, INTER_NEAREST in the middle, INTER_AREA on the right

We hope by now you are familiar with the resize() function in OpenCV. We also saw how to resize an image in a couple of different ways.

The below GIF shows the process of executing the complete code for all the resizing operations that you learned, like resizing by image width and height, scaling factor, and different interpolation methods.

See the Resizing Feature in Action in a Web App

Now that you have  a clear idea about the resize function and its usability, why not try it in a web app. See the effects of resizing there too. We have created a small demo application for the resize() function using Streamlit. You can visit the application page here. Play around with the image provided, or upload one of your choice.

Summary

You learned to resize an image, using custom height and width. You also saw how using the scaling factor kept the aspect ratio intact, ensuring the resized image did not look distorted. We also discussed different types of interpolation methods.

You can find the Colab Notebook for this post here.



Do try out the app we have provided to see the resize function of an image in action. We recommend you download the code for study and practice. Feel free to reach out to us in the comment section for any doubts/feedback or suggestions. 

This course is available for FREE only till 22nd Nov.
FREE Python Course
We have designed this Python course in collaboration with OpenCV.org for you to build a strong foundation in the essential elements of Python, Jupyter, NumPy and Matplotlib.
FREE OpenCV Crash Course
We have designed this FREE crash course in collaboration with OpenCV.org to help you take your first steps into the fascinating world of Artificial Intelligence and Computer Vision. The course will be delivered straight into your mailbox.
 

Get Started with OpenCV

Subscribe to receive the download link, receive updates, and be notified of bug fixes

seperator

Which email should I send you the download link?

Subscribe To Receive
We hate SPAM and promise to keep your email address safe.​
Subscribe Now
About LearnOpenCV

Empowering innovation through education, LearnOpenCV provides in-depth tutorials,
code, and guides in AI, Computer Vision, and Deep Learning. Led by Dr. Satya Mallick, we're dedicated to nurturing a community keen on technology breakthroughs.

Copyright © 2024 – BIG VISION LLC Privacy Policy Terms and Conditions