Quantcast
Channel: CodeSection,代码区,Python开发技术文章_教程 - CodeSec
Viewing all articles
Browse latest Browse all 9596

一个 Pillow 实现的图像填充函数

$
0
0

Pillow,即PIL,python Imaging Library,中文是“枕头”。Pillow是Python平台中图像处理的标准库,功能非常强大,API简单易用。

本文分享一个Pillow实现的图像填充函数 pad_image ,用于预处理图像数据集。在目标检测算法中,需要把输入图像,转换为,模型所需尺寸的图像,同时,保持比例不变,其余部分用灰色填充。

函数的具体实现,如下:

计算图像缩放之后的宽高,等比例缩小或扩大; 调用resize(),改变图像的尺寸; 新建new()目标尺寸target_size的图像; 调用paste()贴图,将缩放后的原始图像,放入目标图像中。

实现如下:

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() 复制代码

原图:


一个 Pillow 实现的图像填充函数

修改:


一个 Pillow 实现的图像填充函数

OK, that's all! Enjoy it!

更多算法技巧,关注微信公众号: 深度算法 (ID: DeepAlgorithm)


Viewing all articles
Browse latest Browse all 9596

Latest Images

Trending Articles



Latest Images