Other answers perform a fixed size (width, height) . If you want to resize to a specific size while maintaining aspect ratio, use this
def ResizeWithAspectRatio(image, width=None, height=None, inter=cv2.INTER_AREA): dim = None (h, w) = image.shape[:2] if width is None and height is None: return image if width is None: r = height / float(h) dim = (int(w * r), height) else: r = width / float(w) dim = (width, int(h * r)) return cv2.resize(image, dim, interpolation=inter)
Example
Example
image = cv2.imread('img.png') resize = ResizeWithAspectRatio(image, width=1280) # Resize by width OR # resize = ResizeWithAspectRatio(image, height=1280) # Resize by height cv2.imshow('resize', resize) cv2.waitKey()
source share