The Wayback Machine - https://web.archive.org/web/20241001173609/https://www.geeksforgeeks.org/image-resizing-using-opencv-python/
Open In App

Image Resizing using OpenCV | Python

Last Updated : 09 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Image resizing refers to the scaling of images. Scaling comes in handy in many image processing as well as machine learning applications. It helps in reducing the number of pixels from an image and that has several advantages e.g. It can reduce the time of training of a neural network as the more the number of pixels in an image more is the number of input nodes that in turn increases the complexity of the model.
It also helps in zooming in on images. Many times we need to resize the image i.e. either shrink it or scale it up to meet the size requirements. OpenCV provides us several interpolation methods for resizing an image.

Choice of Interpolation Method for Resizing:

  • cv2.INTER_AREA: This is used when we need to shrink an image.
  • cv2.INTER_CUBIC: This is slow but more efficient.
  • cv2.INTER_LINEAR: This is primarily used when zooming is required. This is the default interpolation technique in OpenCV.

Syntax: cv2.resize(source, dsize, dest, fx, fy, interpolation)

Parameters:

  • source: Input Image array (Single-channel, 8-bit or floating-point) 
  • dsize: Size of the output array
  • dest: Output array (Similar to the dimensions and type of Input image array) [optional]
  • fx: Scale factor along the horizontal axis  [optional]
  • fy: Scale factor along the vertical axis  [optional]
  • interpolation: One of the above interpolation methods  [optional]

Below is the code for resizing: 

Python
import cv2
import matplotlib.pyplot as plt

image = cv2.imread(r"D:\sims\eb\sim21\EB-ML-06-10-2022-Test-Output-15\PERFORATION\Overkill\Fail\Blister 1 2022-03-12 12-59-43.859 T0 M0 G0 3 PERFORATION Mono.bmp", 1)
# Loading the image

half = cv2.resize(image, (0, 0), fx = 0.1, fy = 0.1)
bigger = cv2.resize(image, (1050, 1610))

stretch_near = cv2.resize(image, (780, 540), 
               interpolation = cv2.INTER_LINEAR)


Titles =["Original", "Half", "Bigger", "Interpolation Nearest"]
images =[image, half, bigger, stretch_near]
count = 4

for i in range(count):
    plt.subplot(2, 2, i + 1)
    plt.title(Titles[i])
    plt.imshow(images[i])

plt.show()

Output: 


Note: One thing to keep in mind while using the cv2.resize() function is that the tuple passed for determining the size of the new image ((1050, 1610) in this case) follows the order (width, height) unlike as expected (height, width).

Image Resizing using OpenCV | Python – FAQs

How to resize images using OpenCV?

To resize an image using OpenCV, you use the cv2.resize() function. This function takes an image and resizes it to the specified dimensions.

import cv2

# Load the image
image = cv2.imread('image.jpg')

# Resize the image
resized_image = cv2.resize(image, (width, height))

What are the parameters for resizing images in OpenCV?

The cv2.resize() function has several parameters:

  • src: The source image to resize.
  • dsize: The desired size of the output image as a tuple (width, height).
  • fx and fy: Scale factors along the x and y axis (optional, used instead of dsize).
  • interpolation: The interpolation method to use (optional). Common options include:
    • cv2.INTER_NEAREST
    • cv2.INTER_LINEAR (default)
    • cv2.INTER_CUBIC
    • cv2.INTER_LANCZOS4

How to maintain aspect ratio when resizing images in Python?

To maintain the aspect ratio, you need to calculate the new dimensions based on the desired size while preserving the original aspect ratio.

import cv2

# Load the image
image = cv2.imread('image.jpg')

# Get the original dimensions
(h, w) = image.shape[:2]

# Desired width
new_width = 800

# Calculate the aspect ratio
aspect_ratio = h / w
new_height = int(new_width * aspect_ratio)

# Resize the image
resized_image = cv2.resize(image, (new_width, new_height))

What are the common algorithms for image resizing in OpenCV?

OpenCV provides several interpolation algorithms for resizing:

  • cv2.INTER_NEAREST: Nearest-neighbor interpolation.
  • cv2.INTER_LINEAR: Bilinear interpolation (default).
  • cv2.INTER_CUBIC: Bicubic interpolation.
  • cv2.INTER_LANCZOS4: Lanczos interpolation over 8×8 neighborhood.

How does image resizing affect image quality in Python?

Resizing can affect image quality in several ways:

  • Loss of Detail: Reducing the size can cause loss of detail and make the image appear blurry.
  • Artifact Introduction: Enlarging an image might introduce artifacts or make it appear pixelated.
  • Interpolation Artifacts: The choice of interpolation method can affect the smoothness and sharpness of the resized image.

Choosing an appropriate interpolation method and being mindful of the resizing ratio can help mitigate quality loss.



Previous Article
Next Article

Similar Reads

Image resizing using Seam carving using OpenCV in Python
Seam carving is an effective image processing technique with the help of which an image can be resized without removing important elements from the image. The basic approach is to find all the continuous pixels with low energy from left to right or from top to bottom. After the region is selected, it is removed from the original image, leaving only
2 min read
Python OpenCV - Bicubic Interpolation for Resizing Image
Image resizing is a crucial concept that wishes to augment or reduce the number of pixels in a picture. Applications of image resizing can occur under a wider form of scenarios: transliteration of the image, correcting for lens distortion, changing perspective, and rotating a picture. The results of resizing greatly vary looking on the kind of inte
9 min read
Node.js Image Upload, Processing and Resizing using Sharp package
Often in our web applications, we need to store multiple forms and formats of images, in the form of a profile picture or an image for a product in an e-commerce prototype. In most of our cases, we need to store images compressed to multiple sizes, retaining the quality. For example, for a product at an e-commerce site, we would require storing 3 v
3 min read
Image Resizing in Matlab
Prerequisite : RGB image representation MATLAB stores most images as two-dimensional matrices, in which each element of the matrix corresponds to a single discrete pixel in the displayed image. Some images, such as truecolor images, represent images using a three-dimensional array. In truecolor images, the first plane in the third dimension represe
2 min read
Mahotas - Resizing Image
In this article we will see how we can resize the image in mahotas. Image interpolation occurs when you resize or distort your image from one pixel grid to another. Image resizing is necessary when you need to increase or decrease the total number of pixels, whereas remapping can occur when you are correcting for lens distortion or rotating an imag
2 min read
Dynamically Resize Buttons When Resizing a Window using Tkinter
Prerequisite: Python GUI – tkinter Button size is static, which means the size of a button cannot be changed once it is defined by the user. The problem here is while resizing the window size, it can affect the button size problem. So the solution here is, make a dynamic button, which means the button size will change as per window size. Let's unde
2 min read
Convert OpenCV image to PIL image in Python
OpenCV is a huge open-source library for computer vision, machine learning, and image processing. OpenCV supports a wide variety of programming languages like Python, C++, Java, etc. It can process images and videos to identify objects, faces, or even the handwriting of a human. When it is integrated with various libraries, such as Numpy which is a
3 min read
Expanding the Canvas Without Resizing in Python Pillow
The Python Imaging Library (PIL) is a powerful tool for image processing in Python, offering a wide range of functionalities from basic image manipulations to complex operations. One of the useful features of PIL is the ability to expand the canvas of an image without resizing the original content. This article explores the concept of expanding the
4 min read
OpenCV - Facial Landmarks and Face Detection using dlib and OpenCV
Content has been removed on Author's request.
1 min read
Automatic Document Scanner using OpenCV (OpenCV Document Scanner)
An automatic document scanner using OpenCV is a computer vision application that automatically detects and extracts documents from images. This type of scanner can be useful in various scenarios, such as digitizing paper documents, processing scanned documents, or automating document recognition tasks. In this article, we will see how we can build
6 min read
PyQt5 – How to stop resizing of window | setFixedSize() method
In this article, we will see how to stop resizing of the main window. While making a window, we get options like going full screen and using cursor to change its size. By using setFixedSize() method we can prevent the resizing of the image. Syntax : self.setFixedSize(width, height) Argument : It takes two integer as argument i.e width and height. A
1 min read
PyQt5 QSpinBox - Resizing it according to value
In this article we will see how we can resize the spin box according to its value. We can set the dimension of the spin box with the help of setGeometry method although it takes position argument as well therefore resizing it is not appropriate. In order to do this we use resize method with the spin box object. Syntax : spin_box.resize(width, heigh
2 min read
MoviePy – Resizing Video File
In this article, we will see how we can resize video file clips in MoviePy. MoviePy is a Python module for video editing, which can be used for basic operations on videos and GIF's. Resizing video files means. Image/frame interpolation occurs when you resize or distort your frame of video from one-pixel grid to another. Video resizing is necessary
3 min read
PYGLET – Setting Size / Resizing of Window
In this article we will see how we can set the size of the window in PYGLET module in python. Pyglet is easy to use but powerful library for developing visually rich GUI applications like games, multimedia etc. A window is a "heavyweight" object occupying operating system resources. Windows may appear as floating regions or can be set to fill an en
2 min read
Allowing resizing window in PyGame
In this article, we will learn How to allow resizing a PyGame Window. Game programming is very rewarding nowadays and it can also be used in advertising and as a teaching tool too. Game development includes mathematics, logic, physics, AI, and much more and it can be amazingly fun. In python, game programming is done in pygame and it is one of the
2 min read
Transition from OpenCV 2 to OpenCV 3.x
OpenCV is one of the most popular and most used Computer vision libraries. It contains tools to carry out image and video processing. When OpenCV 3..4.1 is an improved version of OpenCV 2.4 as it introduced new algorithms and features. Although some of the existing modules were rewritten and moved to sub-modules. In this articles, I will focus on t
2 min read
Top Books for Learning OpenCV: Computer Vision with OpenCV Library
OpenCV or Open Source Computer Vision Library, is an open-source computer vision and machine learning software library. It's extensively used for real-time computer vision tasks such as object detection, face recognition, image processing, etc. Whether you're a beginner or an experienced developer looking to deepen your understanding of OpenCV, her
5 min read
Find the Solidity and Equivalent Diameter of an Image Object Using OpenCV Python
In this article, we will see how we can find the solidity and the equivalent diameter of an object present in an image with help of Python OpenCV. Function to Find Solidity The solidity of an image is the measurement of the overall concavity of a particle. We can define the solidity of an object as the ratio of the contour area to its convex hull a
4 min read
Python | Detect corner of an image using OpenCV
OpenCV (Open Source Computer Vision) is a computer vision library that contains various functions to perform operations on Images or videos. OpenCV library can be used to perform multiple operations on videos. Let's see how to detect the corner in the image. cv2.goodFeaturesToTrack() method finds N strongest corners in the image by Shi-Tomasi metho
2 min read
Image Pyramid using OpenCV | Python
Image Pyramids are one of the most beautiful concept of image processing.Normally, we work with images with default resolution but many times we need to change the resolution (lower it) or resize the original image in that case image pyramids comes handy. The pyrUp() function increases the size to double of its original size and pyrDown() function
1 min read
Negative transformation of an image using Python and OpenCV
Image is also known as a set of pixels. When we store an image in computers or digitally, it’s corresponding pixel values are stored. So, when we read an image to a variable using OpenCV in Python, the variable stores the pixel values of the image. When we try to negatively transform an image, the brightest areas are transformed into the darkest an
4 min read
Python | Image blurring using OpenCV
Image Blurring refers to making the image less clear or distinct. It is done with the help of various low pass filter kernels. Advantages of blurring: It helps in Noise removal. As noise is considered as high pass signal so by the application of low pass filter kernel we restrict noise. It helps in smoothing the image. Low intensity edges are remov
2 min read
Find Circles and Ellipses in an Image using OpenCV | Python
To identify circles, ellipses, or in general, any shape in which the pixels are connected we use the SimpleBlobDetector() function of OpenCV. In non-technical terms, a blob is understood as a thick liquid drop. Here, we are going to call all shapes a blob. Our task is to detect and recognize whether the blob is a circle or not. OpenCV provides a co
2 min read
Image Translation using OpenCV | Python
Translation refers to the rectilinear shift of an object i.e. an image from one location to another. If we know the amount of shift in horizontal and the vertical direction, say (tx, ty) then we can make a transformation matrix e.g. [Tex] \begin{bmatrix} 1 & 0 & tx \\ 0 & 1 & ty \end{bmatrix} [/Tex] where tx denotes the shift along
2 min read
Python | Detect Polygons in an Image using OpenCV
Approach : The approach we would be used to detect the shape of a given polygon will be based on classifying the detected shape on the basis of a number of sides it has. For example, if the detected polynomial has 3 sides, then it could be considered as a triangle, if the polynomial has 4 sides then it could be classified as a square or a rectangle
2 min read
Image Steganography using OpenCV in Python
Image Steganography is the process of hiding secret data in some image. In this post, we will hide one image inside another and convert it into another image and then extract back both the images from the previous image. The idea behind image-based Steganography is very simple. Images are composed of digital data (pixels), which describes what’s in
3 min read
Create Local Binary Pattern of an image using OpenCV-Python
In this article, we will discuss the image and how to find a binary pattern using the pixel value of the image. As we all know, image is also known as a set of pixels. When we store an image in computers or digitally, it’s corresponding pixel values are stored. So, when we read an image to a variable using OpenCV in Python, the variable stores the
5 min read
Log transformation of an image using Python and OpenCV
Logarithm value of a number is a number that raises power to a base number which gives the same number as in input. Simply, the logarithm is the inversion of exponential value of a number. log(exp(x)) = x How log value of a number is calculated? Let's see an example, [Tex]2^3 = 8[/Tex] By applying logarithm in both sides, log(2^3) = log(8) 3 * log(
3 min read
Point Processing in Image Processing using Python-OpenCV
OpenCV is the huge open-source library for computer vision, machine learning, and image processing and now it plays a major role in real-time operation which is very important in today’s systems. By using it, one can process images and videos to identify objects, faces, or even the handwriting of a human. Point processing in spatial domain All the
3 min read
Set Countdown timer to Capture Image using Python-OpenCV
Prerequisites: Introduction to OpenCV Most of us have already captured image using countdown timer with our phones. We can do the same thing on our computer with the help of OpenCV. But here we can specify the countdown timer instead of choosing one of the specified countdown and whenever the particular key will be pressed (let’s say q) the countdo
3 min read
Practice Tags :