from PIL import Image
import os
import glob
def crop(im, height, width):
# im = Image.open(infile)
imgwidth, imgheight = im.size
for i in range(int(imgheight // height)):
for j in range(int(imgwidth // width)):
# print (i,j)
box = (j * width, i * height, (j + 1) * width, (i + 1) * height)
yield im.crop(box)
if __name__ == '__main__':
# change the path and the base name of the image files
imgdir = 'B:\\path\\new\\ZYW_ADV_G'
basename = '*.pgm'
filelist = glob.glob(os.path.join(imgdir, basename))
print(filelist)
for infile in filelist:
# infile='/Users/alex/Documents/PTV/test_splitter/cal/Camera 1-1-9.pgm'
print(infile)
name = infile.split('\\')[-1].split('.')[0]
im = Image.open(infile)
imgwidth, imgheight = im.size
print('Image size is: %d x %d ' % (imgwidth, imgheight))
height = imgheight // 2
width = imgwidth // 2
start_num = 0
for k, piece in enumerate(crop(im, height, width), start_num):
img = Image.new('L', (width, height), 255)
# print img
img.paste(piece)
path = os.path.join(imgdir + '\\' + name+"_%d.pgm" % int(k + 1))
img.save(path)
原图
裁剪后结果
参考