这是一个函数,它从四面八方重叠分割图像。
在边框上,它将用零填充。
它的本质是:它创建一个具有零填充的更大图像,然后以window_size 的步幅提取大小为window_size+2*margin 的补丁。
(您可能需要根据需要进行调整)
def split(img, window_size, margin):
sh = list(img.shape)
sh[0], sh[1] = sh[0] + margin * 2, sh[1] + margin * 2
img_ = np.zeros(shape=sh)
img_[margin:-margin, margin:-margin] = img
stride = window_size
step = window_size + 2 * margin
nrows, ncols = img.shape[0] // window_size, img.shape[1] // window_size
splitted = []
for i in range(nrows):
for j in range(ncols):
h_start = j*stride
v_start = i*stride
cropped = img_[v_start:v_start+step, h_start:h_start+step]
splitted.append(cropped)
return splitted
运行这个
img = np.arange(16).reshape(4,4)
out = split(img, window_size=2, margin=1)
会回来
[array([[ 0., 0., 0., 0.],
[ 0., 0., 1., 2.],
[ 0., 4., 5., 6.],
[ 0., 8., 9., 10.]]),
array([[ 0., 0., 0., 0.],
[ 1., 2., 3., 0.],
[ 5., 6., 7., 0.],
[ 9., 10., 11., 0.]]),
array([[ 0., 4., 5., 6.],
[ 0., 8., 9., 10.],
[ 0., 12., 13., 14.],
[ 0., 0., 0., 0.]]),
array([[ 5., 6., 7., 0.],
[ 9., 10., 11., 0.],
[13., 14., 15., 0.],
[ 0., 0., 0., 0.]])]