python裁剪png图片文件

读取文件夹下的png文件,然后进行裁剪。示例为将1024*1024裁剪为256*256的16开图片,在原始文件夹的文件编码规则为00001,裁剪后的编码为00001+行号+列号(行列号为裁剪后图片左上角像素坐标)

 

from PIL import Image
import os

def crop_image(image_path, output_path, crop_size, code):
    with Image.open(image_path) as img:
        width, height = img.size
        for i in range(0, width, crop_size):
            for j in range(0, height, crop_size):
                box = (i, j, i + crop_size, j + crop_size)
                cropped_img = img.crop(box)
                cropped_img.save(os.path.join(output_path, code+f"{i}_{j}.png"))
                print(code, f"{i}_{j}.png")

image_path = "label"
output_path = "LAB"
if not os.path.exists(output_path):
    os.makedirs(output_path)
crop_size = 256

count = 0

for filename in os.listdir(image_path):
    if filename.endswith(".png"):
        count += 1
        code = f'{count:05d}' #编码规则
        image_file = os.path.join(image_path, filename)
        crop_image(image_file, output_path, crop_size, code)

 

posted @ 2023-05-09 15:32  yokon  阅读(106)  评论(0)    收藏  举报