带重叠区域的影像裁剪(python代码)

最近被催了好几次的带重叠区域的影像裁剪代码终于上新了

带重叠区域的影像裁剪(python代码)_第1张图片


话不多说,直接上代码

import numpy as np
from skimage import io
import os
import tqdm
import math

def cutimg_overlap(in_dir,out_dir,file_type,cutshape,overlap_factor,out_type):   
    if not os.path.exists(out_dir):
        os.makedirs(out_dir)
    data_dir_list, _ = get_file_names(in_dir, file_type)
    count = 0
    print('Cut begining for ', str(len(data_dir_list)), ' images.....' )
    for each_dir in tqdm.tqdm(data_dir_list):
        img= io.imread(each_dir)
        print(img.shape)
        factor1 = int(math.ceil(img.shape[0]/overlap_factor))
        factor2 = int(math.ceil(img.shape[1]/overlap_factor))
        for i in range(factor2):
            for ii in range(factor1):
                start_x = ii*cutshape-ii*overlap_factor
                end_x = (ii+1)*(cutshape)-ii*overlap_factor
                start_y = i*cutshape-i*overlap_factor
                end_y= (i+1)*cutshape-i*overlap_factor
                if end_x>img.shape[0]:
                    start_x= img.shape[0]-cutshape
                    end_x = img.shape[0]
                if end_y>img.shape[1]:
                    start_y= img.shape[1]-cutshape
                    end_y = img.shape[1]
                img_temp = img[start_x:end_x,start_y:end_y,:]
                out_dir_images = out_dir + '/' + each_dir.split('/')[-1].split('.')[0] \
                                    + '_' + str(start_x) + '_' + str(end_x) + '_' + str(start_y) + '_' + str(end_y) + '.' + out_type
                #print('out_dir_images:',out_dir_images)
                io.imsave(out_dir_images,img_temp)
                if end_x==img.shape[0] and end_y==img.shape[1]:
                    break

if __name__ == '__main__':
    ##### cut
    data_dir = './data/A'
    out_dir = './data/A_CUT'
    file_type = ['tif']
    out_type = 'tif'
    cutshape = 1024
    overlap_factor = 512

    cutimg_overlap(data_dir,out_dir,file_type,cutshape,overlap_factor,out_type)

原图

带重叠区域的影像裁剪(python代码)_第2张图片

 裁剪后图像

带重叠区域的影像裁剪(python代码)_第3张图片

带重叠区域的影像裁剪(python代码)_第4张图片

 

整理不易,欢迎一键三连~~

你可能感兴趣的:(基本知识,画图合集,python,pycharm,机器学习)