1

Given an input image test.png, how to resize it (downsizing) such that it fits in a 400x500 pixels box, keeping aspect ratio?

Is it possible directly with cv2.resize, or do we have to compute the sizing factor manually?

1

2 Answers 2

5

It seems there is no helper function for this already built-in in cv2. Here is a working solution:

maxwidth, maxheight = 400, 500

import cv2
img = cv2.imread('test2.png')
f1 = maxwidth / img.shape[1]
f2 = maxheight / img.shape[0]
f = min(f1, f2)  # resizing factor
dim = (int(img.shape[1] * f), int(img.shape[0] * f))
resized = cv2.resize(img, dim)
cv2.imwrite('out.png', resized)
Sign up to request clarification or add additional context in comments.

Comments

1

Answer of @Basj as a function:

def resize_image_to_fit_to_box(img: np.array, max_width: int, max_height: int):
    f1 = max_width / img.shape[1]
    f2 = max_height / img.shape[0]
    f = min(f1, f2)  # resizing factor
    
    # Img fits already into dimensions
    if f >= 1:
        return img
    
    dim = (int(img.shape[1] * f), int(img.shape[0] * f))
    resized = cv2.resize(img, dim)
    return resized

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.