How to Resize Image with OpenCV in Python

Resizing an image with OpenCV in Python is straightforward using the cv2.resize() function.

This function allows you to specify the new image size either by directly setting the width and height or by using a scaling factor.

Example 1: Resizing by Setting Width and Height

import cv2
import numpy as np

# Load the image
image = cv2.imread('Twin.png')

# Define the new width and height
new_width = 800
new_height = 600

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

# Resize original image to match the height of resized image, if necessary
resized_original = cv2.resize(image, (int(image.shape[1] * (new_height / image.shape[0])), new_height))

# Concatenate images horizontally
combined_image = np.hstack((resized_original, resized_image))

# Display the combined image
cv2.imshow('Original and Resized Image', combined_image)

# Wait for a key press to close the window
cv2.waitKey(0)
cv2.destroyAllWindows()

Output

Output_of_Resizing_by_Setting_ Width_and_Height

Example 2: Resizing Using a Scaling Factor

If you wish to resize an image by a specific factor, such as upscaling or downscaling, you can do so as follows:

import numpy as np
import cv2

# Load the image
img = cv2.imread('Twin.png', 1)

# Resize the image (scale down)
# Note: Scaling factors (fx and fy) of 0.5 reduce the size to half
img_scale_down = cv2.resize(img, (0, 0), fx=0.5, fy=0.5)

# Check if the original image and scaled-down image have the same number of channels
if img.shape[2] == img_scale_down.shape[2]:
 # Retrieve the height and width of both images
 h1, w1 = img.shape[:2]
 h2, w2 = img_scale_down.shape[:2]

 # Create an empty matrix large enough to hold both images side by side
 vis = np.zeros((max(h1, h2), w1 + w2, 3), np.uint8)

 # Combine the two images
 # Place the original image on the left
 vis[:h1, :w1, :3] = img
 # Place the scaled-down image on the right
 vis[:h2, w1:w1 + w2, :3] = img_scale_down

 # Display the combined image
 cv2.imshow('Original and Scaled-Down Image Side by Side', vis)
 cv2.waitKey(0)
 cv2.destroyAllWindows()
else:
 print("The original and scaled-down images must have the same number of channels to be displayed side by side.")

Output

Output_of_Resize Image

That’s it.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.