配置参数的文件为Configure.py
class Parameters():
def __init__(self):
self.input_dir = '../data/raw' #大图
self.output_dir = '../data/img_data/'#裁剪输出
self.image_size = 512
批量裁剪程序
import os
import random
from time import sleep
from PIL import Image
from align.Configure import Parameters
para = Parameters()
def main():
sleep(random.random())
op_dir = para.output_dir
if not os.path.exists(op_dir):
os.makedirs(op_dir)
for each_image in os.listdir(para.input_dir):
# 每个图像全路径
image_fullpath = para.input_dir + '/' + each_image
filename = os.path.splitext(os.path.split(image_fullpath)[1])[0]
# PIL库打开每一张图像
img = Image.open(image_fullpath)
# 偏移量
dx = para.image_size
dy = para.image_size
n = 1
# 左上角切割
x1 = 0
y1 = 0
x2 = dx
y2 = dy
[X_Width,Y_Hieght] = img.size
# 纵向
while (x2+dx) <= X_Width:
# 横向切
while (y2+dy) <= Y_Hieght:
output_img = op_dir+filename + str(n) + ".png"
# print n,x1,y1,x2,y2
im2 = img.crop((y1, x1, y2, x2))
im2.save(output_img)
y1 = y1 + dy
y2 = y1 + dy
n = n + 1
x1 = x1 + dx
x2 = x1 + dx
y1 = 0
y2 = dy
if __name__ == '__main__':
main()