Skip to Content

Computer Vision for Developers: How to Fix Image Distortion When Resizing with OpenCV While Preserving Aspect Ratio?

Learn the correct method to resize images without distortion in OpenCV by maintaining aspect ratio. Step-by-step solution for developers facing resizing issues in Computer Vision applications.

Table of Contents

Question

You have an application that uses the following code snippet to set new dimensions for an image while preserving the original aspect ratio.
import cv2
image = cv2.imread(‘welcome.jpg’)
new_width = 500
new_height = 900
new_image = cv2.resize(welcome, (new_width, new_height))
When you run the code, the image comes out distorted. How can you fix this?

A.
import cv2
image = cv2.imread(‘welcome.jpg’)
(h, w) = image.shape[:6]
n_w = 500
aspect_ratio = h/w
n_h = int(n_w * aspect_ratio)
new_image = cv2.resize(image, (n_w, n_h))

B.
import cv2
image = cv2.readit(‘welcome.jpg’)
new_width = 500
new_height = 900
new_image = cv2.size(welcome, (new_width*new_height))

C.
import cv2
image = cv2.imread(‘welcome.jpg’)
new_width = 500
new_height = 900/new_width
new_image = cv2.size(welcome, (new_width, new_height))

D.
import cv
image = cv.imread(‘welcome.jpg’)
(h, w) = image.reshape[:6]
n_w = 500
aspect_ratio = h*w
n_h = int(n_w * aspect_ratio)
new_image = cv.resize(image, (n_w, n_h))

Answer

A.
import cv2
image = cv2.imread(‘welcome.jpg’)
(h, w) = image.shape[:6]
n_w = 500
aspect_ratio = h/w
n_h = int(n_w * aspect_ratio)
new_image = cv2.resize(image, (n_w, n_h))

Explanation

The distortion occurs because the original code forces the image into arbitrary dimensions without preserving the aspect ratio. To fix this, Option A correctly calculates the new height based on the original aspect ratio.

In contrast:

Option B has invalid OpenCV functions and incorrect logic.

Option C miscalculates the aspect ratio using new_height = 900/new_width, unrelated to the original image dimensions.

Option D uses outdated cv syntax and an incorrect aspect ratio formula (h*w instead of h/w).

Final Answer:

import cv2
image = cv2.imread('welcome.jpg')
(h, w) = image.shape[:2] # Correctly extracts height and width
n_w = 500
aspect_ratio = h / w # Preserves original aspect ratio
n_h = int(n_w * aspect_ratio)
new_image = cv2.resize(image, (n_w, n_h))

This ensures the resized image retains its proportions, eliminating distortion.

Computer Vision for Developers skill assessment practice question and answer (Q&A) dump including multiple choice questions (MCQ) and objective type questions, with detail explanation and reference available free, helpful to pass the Computer Vision for Developers exam and earn Computer Vision for Developers certification.