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

好比咱们把一张图像裁剪成每一块都是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拼接测试图
相关文章
相关标签/搜索