from PIL import Image, ImageDraw, ImageOps
def resize_and_pad(image, target_size):
original_width, original_height = image.size
aspect_ratio = original_width / original_height
print(f"aspect_ratio={aspect_ratio}")
if aspect_ratio > 1:
new_width = target_size
new_height = int(target_size / aspect_ratio)
else:
new_height = target_size
new_width = int(target_size * aspect_ratio)
print(f"new_width={new_width},new_height={new_height}")
image = image.resize((new_width, new_height))
pad_width = (target_size - new_width) // 2
pad_height = (target_size - new_height) // 2
print(f"pad_width={pad_width},pad_height={pad_height}")
padding = (pad_width, pad_height, target_size - new_width - pad_width, target_size - new_height - pad_height)
print(f"padding={padding}")
image = ImageOps.expand(image, padding, fill=(0, 0, 0))
return image
img_path = "/Users/yxk/Desktop/test_dataset/fashion-product-images-small/images/39300.jpg"
image = Image.open(img_path).convert('RGB')
#image.show()
print(image.size)
image
结果如下
image_new = resize_and_pad(image,target_size=28)
print(image_new.size)
image_new
image_new.save("./aaa.png")
注意这个最终的效果,这个是按比例进行填充的,首先保持将长边的长度压缩到28,然后将另一边的长度的像素值按比例压缩,埃米尔就会产生一些空白的像素(因为目标的图片大小是正方形),对于空白的像素就用padding进行填充,注意这里的像素值为(0,0,0),即为黑色,而且需要注意的是,有的时候两边填充的像素值是不一样大的,例如上面的例子padding=(3,0,4,0), 图片大小如下
可以看到padding块左边是三个像素,右边是四个像素