按照步长切图

 

 

import cv2 as cv
import numpy as np
import os

import skimage.io


path_img=r'D:\data\compay_build\img' # 切割图像路径
path_label=r'D:\data\compay_build\label' # 切割标签路径




out_width=224
out_height=224

step_width=80
step_height=80
names = os.listdir(path_img)


for name in names:
img = os.path.join(path_img, name)
label=os.path.join(path_label, name)
img = cv.imread(img)
label=skimage.io.imread(label)
h,w,_=img.shape
name, suffix = os.path.splitext(name)
w_exceed=int((w-out_width)//step_width)
h_exceed =int((h-out_height)//step_height)

for i in range(w_exceed):
for j in range(h_exceed):
cv.imwrite('C:/Users/tj/Desktop/unet-master/data/self/train/train_img/' + name + '_'+str(i)+'_'+str(j)+'.png', img[(j*step_height):out_height+step_height*j, i*step_width:out_width+step_width*i].astype(np.uint8))
cv.imwrite('C:/Users/tj/Desktop/unet-master/data/self/train/train_label/' + name + '_' + str(i) + '_' + str(j) + '.png', (label[(j*step_height):out_height+step_height*(j), i*step_width:out_width+step_width*(i)]).astype(np.uint8))
print(name + '_'+str(i)+'_'+str(j)+'.png')


if (w-out_width) % step_width!=0:
for j in range(h_exceed):
cv.imwrite('C:/Users/tj/Desktop/unet-master/data/self/train/train_img/' + name + '_'+str(w_exceed)+'_'+str(j)+'.png', img[(j*step_height):out_height+step_height*(j), -out_width:w].astype(np.uint8))
cv.imwrite('C:/Users/tj/Desktop/unet-master/data/self/train/train_label/' + name + '_' + str(w_exceed) + '_' + str(j) + '.png', (label[(j*step_height):out_height+step_height*(j), -out_width:w]).astype(np.uint8))
print(name + '_'+str(w_exceed)+'_'+str(j)+'.png')

if (h-out_height) % step_height!=0:
for i in range(w_exceed):
cv.imwrite('C:/Users/tj/Desktop/unet-master/data/self/train/train_img/' + name + '_'+str(i)+'_'+str(h_exceed)+'.png', img[-out_height:h, i*step_width:out_width+step_width*(i)].astype(np.uint8))
cv.imwrite('C:/Users/tj/Desktop/unet-master/data/self/train/train_label/' + name + '_' + str(i) + '_' + str(h_exceed) + '.png', (label[-out_height:h, i*step_width:out_width+step_width*(i)]).astype(np.uint8))
print(name + '_'+str(i)+'_'+str(h_exceed)+'.png')
posted @ 2020-04-16 18:08  tangjunjun  阅读(202)  评论(0编辑  收藏  举报
https://rpc.cnblogs.com/metaweblog/tangjunjun