天天看點

【目标檢測】批量裁剪圖檔小腳本

需求

我的需求是批量裁剪某一檔案夾下的所有圖檔,并指定裁剪寬高。

思路

1、 先使用​

​PIL.Image.size​

​​擷取輸入圖檔的寬高。

2、寬高除以2得到中心點坐标

3、根據指定寬高,以中心點向四周拓展

4、調用​​

​PIL.Image.crop​

​完成裁剪

程式

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)      

測試

裁剪前:

【目标檢測】批量裁剪圖檔小腳本