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

比如我们把一张图像裁剪成每一块都是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拼接测试图
posted @ 2018-08-13 15:55  初冬的骄阳  阅读(1513)  评论(0编辑  收藏  举报