【Python】批量裁剪图片小脚本

2022-09-07 15:16:41 浏览数 (1)

需求

我的需求是批量裁剪某一文件夹下的所有图片,并指定裁剪宽高。

思路

1、 先使用PIL.Image.size获取输入图片的宽高。 2、宽高除以2得到中心点坐标 3、根据指定宽高,以中心点向四周拓展 4、调用PIL.Image.crop完成裁剪

程序

代码语言:javascript复制
import os
from PIL import Image


def crop(input_img_path, output_img_path, crop_w, crop_h):
    image = Image.open(input_img_path)
    x_max = image.size[0]
    y_max = image.size[1]
    mid_point_x = int(x_max / 2)
    mid_point_y = int(y_max / 2)
    right = mid_point_x   int(crop_w / 2)
    left = mid_point_x - int(crop_w / 2)
    down = mid_point_y   int(crop_h / 2)
    up = mid_point_y - int(crop_h / 2)
    BOX_LEFT, BOX_UP, BOX_RIGHT, BOX_DOWN = left, up, right, down
    box = (BOX_LEFT, BOX_UP, BOX_RIGHT, BOX_DOWN)
    crop_img = image.crop(box)
    crop_img.save(output_img_path)


if __name__ == '__main__':
    dataset_dir = "cut"  # 图片路径
    output_dir = 'out'  # 输出路径
    crop_w = 300  # 裁剪图片宽
    crop_h = 300  # 裁剪图片高
    # 获得需要转化的图片路径并生成目标路径
    image_filenames = [(os.path.join(dataset_dir, x), os.path.join(output_dir, x))
                       for x in os.listdir(dataset_dir)]
    # 转化所有图片
    for path in image_filenames:
        crop(path[0], path[1], crop_w, crop_h)

测试

裁剪前:

裁剪后:

0 人点赞