python-滑窗法裁剪图片

滑窗法在图像像素级分割领域很常见,尤其是在深度学习语义分割中数据集的制作。下面是我在实际中自编的滑窗法:

# -*- coding: utf-8 -*-
"""
Created on Sat May  2 16:45:25 2020

@author: wzc
"""

import os
import cv2
#import numpy as np
'''滑动窗口'''
def sliding_window(image, stepSize, windowSize,height,width,count):
    
    for y in range(0, image.shape[0], stepSize):
        for x in range(0, image.shape[1], stepSize):
            if (y+windowSize[1])<=height and (x+windowSize[0])<=width:#没超出下边界,也超出下边界
                slide=image[y:y+windowSize[1], x:x+windowSize[0],:]
                slide_shrink = cv2.resize(slide, (256,256), interpolation=cv2.INTER_AREA)
                #slide_shrink_gray = cv2.cvtColor(slide_shrink,cv2.COLOR_BGR2GRAY)
                cv2.imwrite("./slide_rgb/"+str(count)+'.png', slide_shrink)
                count=count+1 #count持续加1
            if (y+windowSize[1])>height and (x+windowSize[0])>width:#超出右边界,但没超出下边界 或者 超出下边界,但没超出右边界
                continue
            if (y+windowSize[1])>height and (x+windowSize[0])<=width:#超出下边界,也超出下边界
                break                  
    return count
                
if __name__=="__main__":
    stepSize=int(0.5*768)#步长就是0.5倍的滑窗大小
    windowSize=[768,768]#滑窗大小
    path=r'G:\农科院实验2019-5-9\unet-重新训练\train_rgb'#文件路径
    count=0
    
    filelist = os.listdir(path)  # 列举图片名
    for item in filelist:
        total_num_file = len(filelist)  # 单个文件夹内图片的总数
        if item.endswith('.jpg') or item.endswith('.JPG'):#查询文件后缀名
            image= cv2.imread(item)
            height,width=image.shape[:2]
            print(height,width)
            
            size1 = (int(round(width/768)*768), int(round(height/768)*768))#round-四舍五入 ;int-图像大小必须是整数 
            print(size1)
            img_shrink = cv2.resize(image, size1, interpolation=cv2.INTER_AREA)#改变图像大小
            count=sliding_window(img_shrink, stepSize, windowSize,size1[1],size1[0],count)#count要返回,不然下一个图像滑窗会覆盖原来的图像
            
详细注释已经加了。有需要的同学可以采用。转载请说明来源于本文,读者的支持是我的最大的动力,有条件的可以打赏一下哈,谢谢。

  • 15
    点赞
  • 50
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 11
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 11
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

撒哈拉的小屋

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

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

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

打赏作者

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

抵扣说明:

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

余额充值