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

该博客分享了一段Python代码,用于实现带重叠区域的影像裁剪。通过`skimage`和`numpy`库,对输入目录中的图像文件按指定尺寸和重叠比例进行裁剪,并保存到新的目录中。裁剪过程考虑了图像边界情况,确保不超出原图范围。适用于大规模遥感影像处理和分析任务。
摘要由CSDN通过智能技术生成

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


话不多说,直接上代码

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)

原图

 裁剪后图像

 

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

评论 18
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

zy_destiny

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值