1.目的
有时候直接进行resize会有形变,所以想到这样的方式,同比例缩放,然后补0。torchvision中是用的PIL。在推理时需要用opencv。
2.实现
参考:https://blog.csdn.net/u010397980/article/details/84889093
def ZeroPaddingResizeCV(img, size=(224, 224), interpolation=None):
isize = img.shape
ih, iw = isize[0], isize[1]
h, w = size[0], size[1]
scale = min(w / iw, h / ih)
new_w = int(iw * scale + 0.5)
new_h = int(ih * scale + 0.5)
img = cv2.resize(img, (new_w, new_h), interpolation)
new_img = np.zeros((h, w, 3), np.uint8)
new_img[(h-new_h)//2:(h+new_h)//2, (w-new_w)//2:(w+new_w)//2] = img
return new_img
3.使用
im = ZeroPaddingResizeCV(im.astype(np.float32) / 255., size=(224, 224))