python批量裁剪图片为800*800尺寸

原图片尺寸大小为720*1280,现要求得到尺寸为800*800的图片,python代码如下:

from PIL import Image
import os

def batch_crop_images(input_dir, output_dir, target_size):
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)

    for filename in os.listdir(input_dir):
        if filename.endswith(".jpg") or filename.endswith(".png"):
            input_path = os.path.join(input_dir, filename)
            output_path = os.path.join(output_dir, filename)

            image = Image.open(input_path)
            width, height = image.size

            new_width = min(width, height)
            new_height = new_width

            left = (width - new_width) / 2
            top = (height - new_height) / 2
            right = left + new_width
            bottom = top + new_height

            cropped_image = image.crop((left, top, right, bottom))
            resized_image = cropped_image.resize(target_size, Image.ANTIALIAS)

            resized_image.save(output_path)

input_directory = '/home/dl/wj/nerf/nerf-pytorch-master/data/nerf_llff_data/cup/images'
output_directory = '/home/dl/wj/nerf/nerf-pytorch-master/data/nerf_llff_data/cup/cut_images'
target_size = (800, 800)

batch_crop_images(input_directory, output_directory, target_size)

代码解释:

        我们首先计算了调整后图像的宽度和高度。我们选择将宽度和高度中的较小值作为新的宽度和高度。这样可以确保裁剪后的图像是一个正方形。

        然后,我们根据新的宽度和高度计算裁剪框的位置,使其位于图像中心。

        接下来,我们使用image.crop方法根据裁剪框裁剪图像,并使用cropped_image.resize方法将裁剪后的图像调整为目标尺寸。

        最后,我们将调整大小后的图像保存到输出路径。

        这种方法将图像裁剪为一个正方形,并在保持图像纵横比的同时,将其调整为填充整个800x800区域。

请记得将'/home/dl/wj/nerf/nerf-pytorch-master/data/nerf_llff_data/cup/images'替换为输入目录的实际路径,将'/home/dl/wj/nerf/nerf-pytorch-master/data/nerf_llff_data/cup/cut_

images'替换为输出目录的实际路径。

    同样,根据需要修改target_size以适应你的要求。

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值