在做数据集处理的时候,遇到了一个问题,文件下面的图片是两张图片结合在一起的,需要从中间切开
然后用下面的代码去运行
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 = 'C:\\Users\\hp\\Desktop\\二合一'
savedir = 'C:\\Users\\hp\\Desktop\\sumiao'
basename = '*.jpg'
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
width = imgwidth // 2
start_num = 0
for k, piece in enumerate(crop(im, height, width), start_num):
# 这一句把图片转化成为了灰度图,我们改成了下一句 还是RGB图片
# img = Image.new('L', (width, height), 255)
img = Image.new('RGB', (width, height), 255)
# print img
img.paste(piece)
path = os.path.join(savedir + '\\' + name+"_%d.jpg" % int(k + 1))
img.save(path)
即可把图片切开了,效果如下: