import cv2 as cv
import numpy as np
import os
import skimage.io
path_img=r'D:datacompay_buildimg' # 切割图像路径
path_label=r'D:datacompay_buildlabel' # 切割标签路径
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_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_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_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_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_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_out_width+step_width*(i)]).astype(np.uint8))
print(name + '_'+str(i)+'_'+str(h_exceed)+'.png')