在深度学习中,在将图片输入模型之前,一般会进行resize操作,如果直接使用cv2.resize(img,size)函数,可能会导致图片变形,从而引起模型推理错误,需要自定义一个能够保持图片宽高比例的resize函数
代码
def make_image(frame, img_size):
img = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
img = ratio_preserving_resize(img, img_size)
return img
def ratio_preserving_resize(image, img_size):
# ratio preserving resize
img_h, img_w = image.shape
scale_h = img_size[1] / img_h
scale_w = img_size[0] / img_w
scale_max = max(scale_h, scale_w)
new_size = (int(img_w * scale_max), int(img_h * scale_max))
image = cv2.resize(image, new_size, interpolation=cv2.INTER_LINEAR)
# pad the image if necessary
pad_height = math.ceil(max(0, img_size[1]-new_size[1])/2)
pad_width = math.ceil(max(0, img_size[0]-new_size[0])/2)
padded_image = cv2.copyMakeBorder(image, pad_height, pad_height, pad_width, pad_width, cv2.BORDER_CONSTANT,value=(0,0,0) )
# center crop
x = padded_image.shape[1] // 2 - img_size[0] // 2
y = padded_image.shape[0] // 2 - img_size[1] // 2
image = padded_image[y:y + img_size[1], x:x + img_size[0]]
return image
测试结果
输入的图片:
1、使用opencv提供的resize函数
img_raw = cv2.imread("./001.png")
img_size = (640, 480)
img = cv2.cvtColor(img_raw, cv2.COLOR_BGR2GRAY)
img = cv2.resize(img,img_size)
win_name = 'Test Resize'
cv2.namedWindow(win_name, cv2.WINDOW_FREERATIO)
while(True):
cv2.imshow(win_name, img)
key = cv2.waitKey(delay=1)
if key == ord('q'):
print('Quitting, \'q\' pressed.')
break
cv2.destroyAllWindows()
2、使用自定义的 ratio_preserving_resize函数
img_raw = cv2.imread("./001.png")
img_size = (640, 480)
img = make_image(img_raw.copy(), img_size)
win_name = 'Test Ratio Preserving Resize'
cv2.namedWindow(win_name, cv2.WINDOW_FREERATIO)
while(True):
cv2.imshow(win_name, img)
key = cv2.waitKey(delay=1)
if key == ord('q'):
print('Quitting, \'q\' pressed.')
break
cv2.destroyAllWindows()