image resize and padding

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块左边是三个像素,右边是四个像素

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值