将图片按一定步长切成小块

# -*- coding = utf-8 -*-
import numpy as np
import cv2
import os
from pathlib import Path
import math

def slice_img(img_dir , x , y):
    
    img_save = Path('./sliced_img_pathlib/')
    img_save.mkdir(exist_ok=True,parents=True)
    
    im = cv2.imread(img_dir,1)
    sum_y,sum_x,_ = im.shape
    gap_x=sum_x%x
    gap_y=sum_y%y
    
    group_x=math.ceil(sum_x/x)
    group_y=math.ceil(sum_y/y)
    lim_x=math.floor(sum_x/x)
    lim_y=math.floor(sum_y/y)
    
    for hy in range(group_y) :
        for hx in range(group_x) :
            new_x1 = hx*x
            new_y1 = hy*y
            new_x2 = x*(hx+1)
            new_y2 = y*(hy+1)
            if new_y2<=sum_y and new_x2<=sum_x:
                new_img=im[new_y1:new_y2,new_x1:new_x2,:]
                
            elif new_y2<=sum_y and new_x2>sum_x:
                new_img=im[new_y1:new_y2,new_x1:,:]
                #new_img=np.pad(new_img, ((0,0),(0,new_x1-wx),(0,0)), 'constant', constant_values=0)
                
            elif new_y2>sum_y and new_x2<=sum_x:
                new_img=im[new_y1:,new_x1:new_x2,:]
                #new_img=np.pad(new_img, ((0,new_y1-hy),(0,0),(0,0)), 'constant', constant_values=0)
                
            else:
                new_img=im[new_y2:,new_x2:,:]
                #new_img=np.pad(new_img, ((0,new_y1-hy),(0,new_x1-wx),(0,0)), 'constant', constant_values=0)
            
            tempfilename = Path(img_dir).stem +'_'+str(new_x1)+'_'+str(new_y1)+'.jpg'
            pic_fname=img_save / tempfilename
            cv2.imwrite(str(pic_fname), new_img,[int(cv2.IMWRITE_JPEG_QUALITY), 100])

slice_img('./2020-04-20.jpg',640,640)