import cv2 import os path = "img_org_path" save_path="img_resize_path" goal_height=540 goal_weight=720 if not os.path.exists(save_path): os.mkdir(save_path) fileList=os.listdir(path) for f in fileList: filePath = os.path.join(path,f) if os.path.isfile(filePath): img = cv2.imread(filePath) # print('img.shape[0]',img.shape[0]) # print('img.shape[1]',img.shape[1]) # print('img.shape[2]',img.shape[2]) height = img.shape[0] weight = img.shape[1] if goal_height / goal_weight <= height / weight: goal_weight_1 = int((height / goal_height) * goal_weight) up1 = 0 up2 = 0 left1 = int((goal_weight_1 - weight) / 2) left2 = goal_weight_1 - weight - left1 img_exp = cv2.copyMakeBorder(img, up1, up2, left1, left2, cv2.BORDER_CONSTANT, value=[0, 0, 0]) img_exp_res = cv2.resize(img_exp, (goal_weight, goal_height), interpolation=cv2.INTER_NEAREST) # img_exp_res = cv2.cvtColor(img_exp_res, cv2.COLOR_RGB2GRAY) # img_exp_res = cv2.resize(img_exp, (goal_weight, goal_height), interpolation=cv2.INTER_CUBIC) else: goal_height_1 = int((goal_height / goal_weight) * weight) up1 = int((goal_height_1 - height) / 2) up2 = goal_height_1 - height - up1 left1 = 0 left2 = 0 img_exp = cv2.copyMakeBorder(img, up1, up2, left1, left2, cv2.BORDER_CONSTANT, value=[0, 0, 0]) img_exp_res = cv2.resize(img_exp, (goal_weight, goal_height), interpolation=cv2.INTER_NEAREST) # img_exp_res = cv2.cvtColor(img_exp_res, cv2.COLOR_RGB2GRAY) cv2.imwrite(save_path + f, img_exp_res)
图像无畸变缩放实现
最新推荐文章于 2020-03-10 11:33:27 发布