pythonopencv

Resize an image with a max width and height, using openCV


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?


Solution

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