Pillow,即PIL,Python Imaging Library,中文是“枕头”。Pillow是Python平台中图像处理的标准库,功能很是强大,API简单易用。python
本文分享一个Pillow实现的图像填充函数pad_image,用于预处理图像数据集。在目标检测算法中,须要把输入图像,转换为,模型所需尺寸的图像,同时,保持比例不变,其他部分用灰色填充。算法
函数的具体实现,以下:微信
实现以下:函数
def pad_image(image, target_size):
iw, ih = image.size # 原始图像的尺寸
w, h = target_size # 目标图像的尺寸
scale = min(float(w) / float(iw), float(h) / float(ih)) # 转换的最小比例
# 保证长或宽,至少一个符合目标图像的尺寸
nw = int(iw * scale)
nh = int(ih * scale)
image = image.resize((nw, nh), Image.BICUBIC) # 缩小图像
# image.show()
new_image = Image.new('RGB', target_size, (128, 128, 128)) # 生成灰色图像
# // 为整数除法,计算图像的位置
new_image.paste(image, ((w - nw) // 2, (h - nh) // 2)) # 将图像填充为中间图像,两侧为灰色的样式
# new_image.show()
return new_image
复制代码
测试:测试
def main():
img_path = 'xxxx.jpg'
image = Image.open(img_path)
size = (416, 416)
pad_image(image, size) # 填充图像
if __name__ == '__main__':
main()
复制代码
原图:spa
修改:code
def preprocess_image(fn_img):
img = cv2.imread(fn_img)
h, w, _ = img.shape
m = h if h > w else w
r = m / 256
h_ = int(h / r)
w_ = int(w / r)
img = cv2.resize(img, (w_, h_))
offset_w = int((256 - w_) / 2)
offset_h = int((256 - h_) / 2)
img_bkg = np.ones((256, 256, 3)) * 255
img_bkg = img_bkg.astype(int)
img_bkg[offset_h:256 - offset_h, offset_w:256 - offset_w] = img
return img_bkg
复制代码
OK, that's all! Enjoy it!cdn
更多算法技巧,关注微信公众号:深度算法(ID: DeepAlgorithm)blog