Monday 14 February 2022

How to do the resizing / letterbox by keeping the aspect ratio?

 def letterbox(img, new_shape=(640, 640), color=(0, 0, 0)):
    # Resize and pad image while meeting stride-multiple constraints
    h,w = img.shape[:2]  # current shape [height, width]

    l = h if h > w else w

    scale = new_shape[0]/l

    h,w = np.array(img.shape[:2])*scale

    resized = cv2.resize(img,(int(w),int(h)))

    dh = max(new_shape[0]-resized.shape[0],0)
    dw = max(new_shape[1]-resized.shape[1],0)

    img = cv2.copyMakeBorder(resized, 0, dh, 0, dw, cv2.BORDER_CONSTANT, value=color)  # add border

    return img #, scale

No comments:

Post a Comment