python cv2 resize keep aspect ratio

Solutions on MaxInterview for python cv2 resize keep aspect ratio by the best coders in the world

showing results for - "python cv2 resize keep aspect ratio"
Leelou
21 Jun 2020
1def image_resize(image, width = None, height = None, inter = cv2.INTER_AREA):
2    # initialize the dimensions of the image to be resized and
3    # grab the image size
4    dim = None
5    (h, w) = image.shape[:2]
6
7    # if both the width and height are None, then return the
8    # original image
9    if width is None and height is None:
10        return image
11
12    # check to see if the width is None
13    if width is None:
14        # calculate the ratio of the height and construct the
15        # dimensions
16        r = height / float(h)
17        dim = (int(w * r), height)
18
19    # otherwise, the height is None
20    else:
21        # calculate the ratio of the width and construct the
22        # dimensions
23        r = width / float(w)
24        dim = (width, int(h * r))
25
26    # resize the image
27    resized = cv2.resize(image, dim, interpolation = inter)
28
29    # return the resized image
30    return resized
31