(适用于彩色图)
图像长短边等比例缩放并填零补成正方形说明:将图像长边缩放至固定尺寸,并将短边等比例缩放,空出部分两边对称填零,补成正方形。
以下是由于opencv读取和保存的通道顺序默认指的不一样,所以分隔通道后再融合。
pil_image = cv2.imread(path_image)
b, g, r = cv2.split(pil_image) # 通道分离,再重新合并操作
pil_image = cv2.merge([r, g, b])
output_image = img_pad(pil_image)
output_image.save(path_output)
完整代码如下:
import os
import numpy as np
from PIL import Image
import cv2
def img_pad(pil_file):
w, h,c= pil_file.shape
fixed_size = 139 # 输出正方形图片的尺寸
if h >= w:
factor = h / float(fixed_size)
new_w = int(w / factor)
if new_w % 2 != 0:
new_w -= 1
pil_file = cv2.resize(pil_file,(new_w, fixed_size))
pad_w = int((fixed_size - new_w) / 2)
array_file = np.array(pil_file)
# array_file = np.pad(array_file, ((0, 0), (pad_w, fixed_size-pad_w)), 'constant')
array_file = cv2.copyMakeBorder(array_file, 0, 0, pad_w, fixed_size-new_w-pad_w, cv2.BORDER_CONSTANT, value=(0, 0, 0))
else:
factor = w / float(fixed_size)
new_h = int(h / factor)
if new_h % 2 != 0:
new_h -= 1
pil_file = cv2.resize(pil_file,(fixed_size, new_h))
pad_h = int((fixed_size - new_h) / 2)
array_file = np.array(pil_file)
# array_file = np.pad(array_file, ((pad_h, fixed_size-pad_h), (0, 0)), 'constant')
array_file = cv2.copyMakeBorder(array_file, pad_h, fixed_size - new_h-pad_h,0, 0, cv2.BORDER_CONSTANT, value=(0, 0, 0))
output_file = Image.fromarray(array_file)
return output_file
if __name__ == "__main__":
dir_image = 'data/positive' # 图片所在文件夹
dir_output = 'data/positiveres' # 输出结果文件夹
if not os.path.exists(dir_output):
os.makedirs(dir_output)
i = 0
list_image = os.listdir(dir_image)
for file in list_image:
path_image = os.path.join(dir_image, file)
path_output = os.path.join(dir_output, file)
pil_image = cv2.imread(path_image)
b, g, r = cv2.split(pil_image) # 通道分离,再重新合并操作
pil_image = cv2.merge([r, g, b])
# pil_image = pil_image.load()
output_image = img_pad(pil_image)
output_image.save(path_output)
i += 1
if i%1000==0:
print('The num of processed images:', i)
结果如下:
原图:
放缩后: