optimal way to resize an image with opencv python

  • Last Update :
  • Techknowledgy :

Resizing an image means changing the dimensions of it, be it width alone, height alone or changing both of them. Also, the aspect ratio of the original image could be preserved in the resized image. To resize an image, OpenCV provides cv2.resize() function.,Following is the original image with dimensions (149,200,4)(height, width, number of channels) on which we shall experiment on :,Concluding this OpenCV Python Tutorial, we have learned how to resize an image in Python using OpenCV resize() function.,Resize only the width (Increase or decrease the width of the image keeping height unchanged)

The syntax of resize function in OpenCV is

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

resize-image.py

import cv2

img = cv2.imread('/home/img/python.png', cv2.IMREAD_UNCHANGED)

print('Original Dimensions : ', img.shape)

scale_percent = 60 # percent of original size
width = int(img.shape[1] * scale_percent / 100)
height = int(img.shape[0] * scale_percent / 100)
dim = (width, height)

# resize image
resized = cv2.resize(img, dim, interpolation = cv2.INTER_AREA)

print('Resized Dimensions : ', resized.shape)

cv2.imshow("Resized image", resized)
cv2.waitKey(0)
cv2.destroyAllWindows()

Output

Original Dimensions: (149, 200, 4)
Resized Dimensions: (89, 120, 4)

Suggestion : 2

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.  ,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.,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. ,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.

#
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()
// 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;
}
# Importing the libraries
import cv2
import numpy as np
#include<opencv2 /opencv.hpp>
   #include<iostream>
      // Namespace to nullify use of cv::function(); syntax
      using namespace std;
      using namespace cv;
# Reading image
image = cv2.imread('image.jpg')
// Reading image
Mat image = imread("image.jpg");

Suggestion : 3

To resize an image in Python, you can use cv2.resize() function of OpenCV library cv2.,Resizing, by default, does only change the width and height of the image. The aspect ratio can be preserved or not, based on the requirement. Aspect Ratio can be preserved by calculating width or height for given target height or width respectively.,In this tutorial of Python Examples, we have learned how to use OpenCV cv2.resize() function, to resize an image along width, height or both by preserving the aspect ratio or not preserving the aspect ratio.,In the following example, we are going to see how we can resize the above image using cv2.resize() while preserving the aspect ratio. We will resize the image to 50% of its actual shape, i.e., we will reduce its height to 50% of its original and width to 50% of its original.

Following is the syntax of cv2.resize() function.

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

Python Program

import cv2

src = cv2.imread('D:/cv2-resize-image-original.png', cv2.IMREAD_UNCHANGED)

#percent by which the image is resized
scale_percent = 50

#calculate the 50 percent of original dimensions
width = int(src.shape[1] * scale_percent / 100)
height = int(src.shape[0] * scale_percent / 100)

# dsize
dsize = (width, height)

# resize image
output = cv2.resize(src, dsize)

cv2.imwrite('D:/cv2-resize-image-50.png', output)

In the dsize, we will keep the width same as that of original image but change the height.

import cv2

src = cv2.imread('D:/cv2-resize-image-original.png', cv2.IMREAD_UNCHANGED)

# set a new height in pixels
new_height = 200

# dsize
dsize = (src.shape[1], new_height)

# resize image
output = cv2.resize(src, dsize, interpolation = cv2.INTER_AREA)

cv2.imwrite('D:/cv2-resize-image-height.png', output)

Suggestion : 4

by Adrian Rosebrock on January 20, 2021

Luckily, OpenCV is pip-installable:

$ pip install opencv - contrib - python

From there, the project folder should look like this:

$ tree.--dirsfirst
   .├──adrian.png└── opencv_resize.py

0 directories, 2 files

But before we get too deep into the details, let’s jump into an example:

#
import the necessary packages
import argparse
import imutils
import cv2

# construct the argument parser and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", type = str,
   default = "adrian.png",
   help = "path to the input image")
args = vars(ap.parse_args())

In the example we explored, we only resized the image by specifying the width. But what if we wanted to resize the image by setting the height? All that requires is a change to computing the resize ratio used to maintain the aspect ratio:

#
let 's resize the image to have a height of 50 pixels, again keeping
# in mind the aspect ratio
r = 50.0 / image.shape[0]
dim = (int(image.shape[1] * r), 50)

# perform the resizing
resized = cv2.resize(image, dim, interpolation = cv2.INTER_AREA)
cv2.imshow("Resized (Height)", resized)
cv2.waitKey(0)

Instead, we can use the imutils.resize function, which automatically handles computing and maintaining aspect ratios for us:

# calculating the ratio each and every time we want to resize an
# image is a real pain, so
let 's use the imutils convenience
#
function which will * automatically * maintain our aspect ratio
#
for us
resized = imutils.resize(image, width = 100)
cv2.imshow("Resized via imutils", resized)
cv2.waitKey(0)

Suggestion : 5

We can downscale or upscale an image when resizing it. Let's downscale the original image to 300x300 pixels:

import cv2

# read the image
image = cv2.imread("image.jpg")
print("Original shape: ", image.shape)

height = 300
width = 300
dimensions = (width, height)
new_image = cv2.resize(image, dimensions, interpolation = cv2.INTER_LINEAR)

print("New shape:      ", new_image.shape)

# display the images
cv2.imshow("Original image", image)
cv2.imshow("Resized image", new_image)
cv2.waitKey(0)
cv2.destroyAllWindows()

output:

Original shape: (400, 600, 3)
New shape: (300, 300, 3)

This way, you are sure that the aspect ratio of the original image will be the same as that of the new image.

import cv2

# read the image
image = cv2.imread("image.jpg")
print("Original shape: ", image.shape)

height = image.shape[0]
width = image.shape[1]

# We want the new image to be 60 % of the original image
scale_factor = 0.6
new_height = int(height * scale_factor)
new_width = int(width * scale_factor)
dimensions = (new_width, new_height)
new_image = cv2.resize(image, dimensions, interpolation = cv2.INTER_LINEAR)

print("New shape:      ", new_image.shape)

cv2.imshow("Original image", image)
cv2.imshow("Resized image", new_image)
cv2.waitKey(0)
cv2.destroyAllWindows()

Here is how to do it:

import cv2

# read the image
image = cv2.imread("image.jpg")
print("Original shape: ", image.shape)

height = image.shape[0]
width = image.shape[1]

#
let 's say we want the new width to be 400px
# and compute the new height based on the aspect ratio
new_width = 400
ratio = new_width / width #(or new_height / height)
new_height = int(height * ratio)

dimensions = (new_width, new_height)
new_image = cv2.resize(image, dimensions, interpolation = cv2.INTER_LINEAR)

print("New shape:      ", new_image.shape)

cv2.imshow("Original image", image)
cv2.imshow("Resized image", new_image)
cv2.waitKey(0)
cv2.destroyAllWindows()

Suggestion : 6

To resize an image using OpenCV, use the cv2.resize() function.,To read an image using OpenCV, you need to import the OpenCV library and use the imread() function.,To resize images with OpenCV, use the cv2.resize() function. It takes the original image, modifies it, and returns a new image.,Today you learned how to resize images using OpenCV and Python.

Here is a quick cheat sheet for resizing images in four ways:

# Read the image
img = cv2.imread('image.jpeg')

# Scale down to 25 %
   p = 0.25
w = int(img.shape[1] * p)
h = int(img.shape[0] * p)
new_img = cv2.resize(img, (w, h))

# Scale up to 150 %
   p = 1.5
w = int(img.shape[1] * p)
h = int(img.shape[0] * p)
new_img = cv2.resize(img, (w, h))

# Change width only
w = 400
h = img.shape[0]
new_img = cv2.resize(img, (w, h))

# Change height only
w = img.shape[1]
h = 300
new_img = cv2.resize(img, (w, h))

For example, if your script is on the same folder with “image.jpeg” you can read the image into your program by:

import cv2

img = cv2.imread('image.jpeg')

The syntax of the cv2.resize() function is:

cv2.resize(src, dsize, fx, fy, interpolation)

For instance, let’s scale the image down to 25% of the original size and show it using the imshow() function.

import cv2

img = cv2.imread('image.jpeg')

p = 0.25
new_width = int(img.shape[1] * p)
new_height = int(img.shape[0] * p)

resized = cv2.resize(img, (new_width, new_height))

cv2.imshow(f "Elephants at scale {p}", resized)

# Hide the image window with any key press
cv2.waitKey()
cv2.destroyAllWindows()

For instance, let’s scale the image up to 150% of the original image:

import cv2

img = cv2.imread('image.jpeg')

p = 1.5
new_width = int(img.shape[1] * p)
new_height = int(img.shape[0] * p)

resized = cv2.resize(img, (new_width, new_height))

cv2.imshow(f "Elephants at scale {p}", resized)

cv2.waitKey()
cv2.destroyAllWindows()