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?
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?
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)
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