Python改变图大小并按照短边居中剪裁的方法

发现Stable Diffusion Webui,Lora-scripts之类的还是不够智能,预处理阶段有这样的需求。目标很简单,把一个超大的图缩小成正方向(如1024*1024),并保留短的一边,长的一边剪裁,并且剪裁过程居中。

问了一下文心一言,基本在它的代码上改了一下:

首先:

pip install Pillow

其次代码如下:

from PIL import Image
import os

size=(1024,1024)
Image.MAX_IMAGE_PIXELS = None

old_path='test'
new_path='new'

counter=0

for filename in os.listdir(old_path):
    if filename.endswith('.jpg'):
        with Image.open(os.path.join(old_path, filename)) as img:

            img_width, img_height=img.size
            ratio_w=size[0]/img_width
            ratio_h=size[1]/img_height
            ratio=max(ratio_w,ratio_h)

            # Calculate the new image size and position
            new_width = int(img_width * ratio)
            new_height = int(img_heigh
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值