OpenCV cv2.resize() Function

Learn via video courses
Topics Covered

Overview

Let's say you are working on a larger number of image data for image classification and your model requires an enormous amount of time to train because data in each image with high dimensionality contains different features.Thus using Python for machine-learning operations through frameworks like Open-source Computer-Vision library plays a significant role in image-related tasks. In this article, we will have a deep understanding of why an image should be resized or scaled and how the OpenCV c2.resize() function works on images to increase or decrease an image's size.

Syntax of OpenCV cv2.resize() Function

The cv2.resize() function is a part of the OpenCV library, which is used for image processing tasks. It is used to resize an image to a specified size or scale. It takes two main arguments: the input image, and the size of the output image.The function has several optional parameters that can be used to specify the interpolation method, the aspect ratio of the output image, and other settings.The Syntax of OpenCV cv2.resize() Function is :

Parameters of OpenCV cv2.resize() Function

The following are the parameters of the cv2.resize() Function.

ParametersDescription
srcinput image (in the form of numpy array)
dsizedesired size of the output image(width,height)-given as tuple
fxscaling factor(along the horizontal axis)
fyscaling factor(along the vertical axis)
interpolationadding/removing pixels-default(cv2.INTER_LINEAR) or it takes one of the below interpolation method

Interpolation Argument

The following are the interpolation methods for adding and removing pixels.

Interpolation argumentDescription
cv2.INTER_NEARESTnearest neighbour interpolation
cv2.INTER_LINEARbilinear interpolation
cv2.INTER_CUBICbicubic interpolation
cv2.INTER_AREAresampling using pixel area relation (preferred for image decimation)
cv2.INTER_LANCZOS4Lanczos interpolation over 8x8 neighborhood

Return Value of OpenCV cv2.resize() Function

  • The cv2.resize() function in OpenCV returns a single value, which is the resized image.
  • The input to this function is the original image that needs to be resized, and the output is the resized image that is created based on the specified parameters.
  • The function modifies the original image to create the resized image, so there is no need to assign the return value to a new variable.
  • The size and aspect ratio of the output image can be controlled by specifying the desired width and height or the scaling factor.
  • Additionally, the function can take an optional interpolation method parameter to control the quality of the resized image.

Exceptions of OpenCV cv2.resize() Function

The cv2.resize() function in OpenCV can raise several exceptions, depending on the specific inputs and parameters used. Some common exceptions include:

1. cv2.error : This is a general error that can occur if the function encounters an unexpected issue. This can happen if the input image or output size is invalid, or if the interpolation method specified is not supported. 1. TypeError : This error can occur if the input or output image is not of the correct type or if the function is called with an invalid parameter. For example, this can happen if the interpolation method specified is not a valid option or if the scaling factor is not a positive number.

How does the OpenCV cv2.resize() Function work?

The cv2.resize() function takes two main input parameters - the source image and the desired output size. The desired output size can be specified either by specifying the new width and height or by a scaling factor. If we specify the new width and height, cv2.resize() calculates the scaling factor needed to achieve the desired output size.

Next, the function interpolates the pixels in the source image to create the resized output image. Several interpolation methods can be used, such as cv2.INTER_LINEAR, cv2.INTER_CUBIC, and cv2.INTER_AREA. These methods differ in the algorithm used to interpolate the pixels.

OpenCV provides the following interpolation methods:

cv2.INTER AREA resamples using the pixel area relation. This is the most effective way to reduce the size of an image. When zooming into an image, it employs the INTER NEAREST method.

cv2.INTER CUBIC resizes using bicubic interpolation. This method computes based on the pixels' 4*4 neighbouring pixels. A new pixel is formed by taking the weighted average of these 16 pixels.

Interpolation with cv2.INTER LINEAR is similar to interpolation with INTER CUBIC. INTER CUBIC, on the other hand, only uses 2*2 neighbouring pixels to calculate the weighted average of the pixels.

cv2.INTER NEAREST interpolates using the nearest neighbour concept. For interpolation, only one neighbouring pixel from the image is used.

Each interpolation method has its own set of advantages and disadvantages. It is possible to be quick but produce poor results.You should select an interpolation method based on your requirements.

  • If the source image has a higher resolution than the desired output size, the cv2.resize() function reduces the number of pixels by averaging the values of neighbouring pixels.
  • Conversely, if the source image has a lower resolution than the desired output size, cv2.resize() interpolates new pixels to fill the gaps.
  • The cv2.resize() function can be used to upscale or downscale images depending on the desired output size.
  • When upscaling an image, it is important to use an interpolation method that can create smooth and continuous transitions between the pixels.
  • Finally, the cv2.resize() function returns the resized image as a NumPy array, which can be further processed or displayed using other OpenCV functions.

Resizing images

Resizing With a Scaling Factor

  • Scaling Factor or Scale Factor is a number that scales or multiplies a quantity, in this case, the width and height of the image.
  • It contributes to maintaining the aspect ratio and the display quality.
  • Thus, the image does not appear distorted when you are upscaling or downscaling it.

Examples

Before diving into examples of the cv2.resize() function in OpenCV, it's important to keep in mind the following points:

  • Resizing an image can result in a loss of information and quality, particularly if the output size is significantly smaller than the input size. Therefore, it's important to carefully consider the desired output size and aspect ratio to avoid losing important details in the image.
  • The cv2.resize() function can be used to both upscale and downscale an image, depending on the desired output size. However, upscaling an image can result in a loss of quality and is generally not recommended.
  • The cv2.resize() function allows for a variety of interpolation methods to be used when resizing an image, each of which has its advantages and disadvantages. Careful consideration of the specific use case and desired output can help determine the best interpolation method to use.

Example 1 - Resize and Preserve Aspect Ratio

Downscaling with cv2.resize()

When downscaling an image using cv2.resize() with a scaling factor, the width and height of the output image are reduced by the same factor. For example, if the scaling factor is 0.5, the output image will have half the width and half the height of the original image.

The cv2.INTER_AREA interpolation method is often used for downsampling, as it works well in preserving edges and minimizing aliasing effects.

When downsampling an image, it is important to consider the original image size and the desired output size to ensure that the output image is not too small to be useful.

Downsampling can be useful for reducing the size of large images or for creating smaller versions of an image for use on the web or in mobile applications.

However, downsampling can also result in a loss of detail and resolution, so it should be used judiciously depending on the specific use case.

Output:

resizing-images 1

Example 2 - Resize and Preserve Aspect Ratio

Upscaling with cv2.resize() To upscale an image using cv2.resize() with a scaling factor, we first load the image using cv2.imread(). Then, we extract the original width and height of the image using the shape attribute. Next, we define a scaling factor, which represents the factor by which we want to increase the size of the image.

We calculate the new width and height of the upscaled image by multiplying the original width and height by the scaling factor. Finally, we use cv2.resize() to upscale the image and display it using cv2.imshow().

Output:

RESIZED IMAGE

Example 3 - Resize and Do not Preserve Aspect Ratio

Resizing an image without preserving the aspect ratio means changing the width and height of the image independently so that the aspect ratio of the original image is not maintained. This can result in the image appearing stretched or distorted. In some cases, it may be necessary to resize an image in this way to fit a particular display or to meet specific requirements for a particular application. However, it is important to note that resizing an image without preserving the aspect ratio can result in a loss of information and a reduction in image quality.

Change width only

This means altering the width of the image while maintaining the aspect ratio of the original image. This can be useful in situations where the width of an image needs to be adjusted to fit a specific display or to meet other requirements while ensuring that the image does not appear distorted or stretched.

However, it is important to note that changing the width of an image without adjusting the height can result in a loss of information and a reduction in image quality, especially if the new width is significantly different from the original width.

Output:

Change width only

Change height only

To change the height only in the cv2.resize() function, you can set the new height value while keeping the width value the same as the original image. This can be done by passing the desired new height value as the second parameter and setting the width parameter to 0 or to the original width value. Here is an example code:

Output:

Change height only

Conclusion

  • The cv2.resize() function allows you to scale up or down by specifying a scaling factor and multiplying the width and height by it.
  • Use cv2.resize() with the original height and a specified width if you only want to change the width.
  • Use cv2.resize() with the original width and a specific height to just change the height.
  • Several interpolation techniques mentioned before are available to modify the output image's quality.