图像滑动窗口分割
import cv2
import os
def sliding_window(image, stepSize, windowSize):
# slide a window across the image
for y in range(0, image.shape[0], stepSize[1]):
for x in range(0, image.shape[1], stepSize[0]):
# yield the current window
yield (x, y, image[y:y + windowSize[1], x:x + windowSize[0]])
# 返回滑动窗结果集合,本示例暂时未用到
def get_slice(image, stepSize, windowSize):
slice_sets = []
for (x, y, window) in sliding_window(image, stepSize, windowSize):
# if the window does not meet our desired window size, ignore it
if window.shape[0] != windowSize[1] or window.shape[1] != windowSize[0]:
continue
slice = image[y:y + windowSize[1], x:x + windowSize[0]]
slice_sets.append(slice)
return slice_sets
if __name__ == '__main__':
dir_ = r'D:DL_Codedatasetseason3_data rain'
dir_result_img = r'D:DL_Codedatasetseason3_dataslide_resultimg'
dir_result_mask = r'D:DL_Codedatasetseason3_dataslide_resultmask'
if os.path.exists(dir_result_img)==False:
os.makedirs(dir_result_img)
if os.path.exists(dir_result_mask)==False:
os.makedirs(dir_result_mask)
file_list = os.listdir(dir_)
for file_ in file_list:
file_name = os.path.join(dir_,file_)
mask_file = file_name.replace('train', 'train_mask').replace('jpg', 'png')
image = cv2.imread(file_name)
mask_image = cv2.imread(mask_file)
# 自定义滑动窗口的大小
w = image.shape[1]
h = image.shape[0]
# 本代码将图片分为3×3,共九个子区域,winW, winH和stepSize可自行更改
(winW, winH) = (int(w/4),int(h/4))
stepSize = (int(w/8), int(h/8))
cnt = 0
for (x, y, window) in sliding_window(image, stepSize=stepSize, windowSize=(winW, winH)):
# if the window does not meet our desired window size, ignore it
if window.shape[0] != winH or window.shape[1] != winW:
continue
slice_img = image[y:y+winH,x:x+winW]
slice_mask = mask_image[y:y+winH,x:x+winW]
#print(slice_img.shape)
mean_mask_value = slice_mask.mean()
#cnt+=1
#print(cnt)
if mean_mask_value==0.0:
save_name_img = os.path.join(dir_result_img,file_[:-4]+'_'+str(cnt)+'.png')
save_name_mask = os.path.join(dir_result_mask,file_[:-4]+'_'+str(cnt)+'.png')
cv2.imwrite(save_name_img,slice_img)
#cv2.imwrite(save_name_mask,slice_mask)
cnt+=1