好比咱們把一張圖像裁剪成每一塊都是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拼接測試圖