导读
在做图像分类的任务中,经常需要将图片resize到指定的尺寸,例如 224,直接resize的结果,会导致图片失真,因此需要对其进行填充操作。

例如我们需要对上面的图片进行resize,直接使用resize 操作得到的结果:

大小:224*224
显然并不是我们想要的结果。
我们希望得到的是:
1、图片大小缩放
2、图片特征不失真(保持长宽比)
保存长宽比的秘诀在于,在较短的一边填充黑色
from PIL import Image
def make_square(im, , fill_color=(0, 0, 0, 0)):
x, y = im.size
size = max(x, y)
new_im = Image.new('RGB', (size, size), fill_color)
new_im.paste(im, (int((size - x) / 2), int((size - y) / 2)))
new_img = new_img.resize((224, 224))
return new_im
test_image = Image.open('test.jpg')
new_image = make_square(test_image)
new_image.show()
new_image.save('result.jpg')最终的结果:
