滑窗法在图像像素级分割领域很常见,尤其是在深度学习语义分割中数据集的制作。下面是我在实际中自编的滑窗法:
# -*- 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要返回,不然下一个图像滑窗会覆盖原来的图像
详细注释已经加了。有需要的同学可以采用。转载请说明来源于本文,读者的支持是我的最大的动力,有条件的可以打赏一下哈,谢谢。