从中间裁剪图片

在做数据集处理的时候,遇到了一个问题,文件下面的图片是两张图片结合在一起的,需要从中间切开
在这里插入图片描述
然后用下面的代码去运行

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)


即可把图片切开了,效果如下:
在这里插入图片描述
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值