python把图片按两条中线裁剪成四张

本文介绍了一个使用Python和PIL库实现的图片裁剪脚本。该脚本能够将一张大图片按照指定的高度和宽度裁剪成多个小图片,适用于批量处理大量图像文件的场景。代码中详细展示了如何读取图片、计算裁剪区域并保存裁剪后的图片。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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)

原图
原图
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
裁剪后结果
参考

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值