python 将图片切割成固定大小的图片脚本

将像素很大的图片切割成固定大小的多张图片,代码如下:
import numpy as np
import matplotlib
import os
from PIL import Image

def img_seg(dir):
    files = os.listdir(dir)
    for file in files:
        a, b = os.path.splitext(file)
        img = Image.open(os.path.join(dir + "/" + file))
        hight, width = img.size
        w = 812    #切割成812*812
        id = 1
        i = 0
        while (i + w <= hight):
            j = 0
            while (j + w <= width):
                new_img = img.crop((i, j, i + w, j + w)
                rename = "./pic3/"
                new_img.save(rename + a + "_" + str(id) + b)
                id += 1
                j += 50   #滑动步长
            i = i + 50


if __name__ == '__main__'
    path = "./2"
    img_seg(path)

你可能感兴趣的:(深度学习,数据集)