把图像裁剪或者切割成相同大小的子图像,并且可以设置子图像相互重叠的像素...

比如我们把一张图像裁剪成每一块都是448*448 ,并且重叠像素设置120个像素 如果不需要则可以设置为0
我们使用python的pillow模块 没安装的话请安装这个模块再cmd中 使用 pip install pillow 命令安装该模块
 
import os
from PIL import Image
 
def splitimage(src,rownum,colnum,dstpath,overlap_pix):
    """
    The image is cut to a fixed size and the overlap rate can be set; if overlap_pix = 0 Each image will not overlap
    Args:
        src: image file  path.
        rownum,colnum:The size of each image after cutting
        dstpath: save slice path
        overlap_pix:  Overlapping pixels
       
   
   
    """
    if os.path.exists(src) :
        print('文件存在')
    else:
        print('文件不存在')
        return
   
    if  os.path.isdir(dstpath) :
        print('文件夹不存在,则创建')
        pass
    else:
        os.mkdir(dstpath)
   
   
    img = Image.open(src)
   
    w, h = img.size
   
    if rownum <= h and colnum <= w:
        print('Original image info: %sx%s, %s, %s' % (w, h, img.format, img.mode))
        print('开始处理图片切割, 请稍候...')
 
        s = os.path.split(src)
        if dstpath == '':
            dstpath = s[0]
        fn = s[1].split('.')
      
        ext = fn[-1]
 
        num = 0
       
       
       
        rowheight = h // (rownum-overlap_pix) + 1
        colwidth = w // (colnum -overlap_pix) + 1
       
       
        for r in range(rowheight):
            for c in range(colwidth):
               
                Lx = (c * colnum) - overlap_pix * c
                Ly = (r * rownum) - overlap_pix * r
               
                if(Lx<=0 ):
                    Lx = 0
                   
                if( Ly <= 0):
                    Ly = 0
                   
                Rx = Lx + colnum
                Ry = Ly + rownum   
                   
                  
                box = (Lx,Ly, Rx,Ry)
                img.crop(box).save(os.path.join(dstpath,str(Lx)+'_'+str(Ly) + '_' + str(num) + '.' + ext))
                # crop(left, upper, right, lower) 名字中带有图像坐标
                num = num + 1
 
        print('图片切割完毕,共生成 %s 张小图片。' % num)
    else:
        print('不合法的行列切割参数!')
 
 

               
def main():
    jpg_image_path = r'F:\function_test\caijian\data\1.jpg'
    save_path =  r'F:\function_test\caijian\data\slice3'
    row = 448
    col = 448
    overlap_pix = 120
    splitimage(jpg_image_path,row, col, save_path,overlap_pix)
              
   
   
if __name__=='__main__':
    main()
结果:结果如下图,那个ps文件不是程序的结果,ps文件时我是用ps拼接这些小图测试,第二张图是我用ps拼接测试图

转载于:https://www.cnblogs.com/lixiunan/p/9468720.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值