我在使用CNN进行体数据分类以分割图像。我使用嵌套的for循环来生成用于神经网络的补丁,但由于我的图像是三维的,这个过程非常耗时。
有没有我没有想到的优化方法?
def data_gen(image, labels, patch_size):""":param image: 3维的图像numpy矩阵:param labels: 3维的掩码numpy矩阵:param patch_size: 所需的补丁尺寸:return: 补丁数组和标签数组"""Patch_array = np.array([])Label_array = np.array([])PS = (patch_size - 1)/2npad = ((PS, PS), (PS, PS), (PS,PS))# 用零填充整个图像以便在边缘生成补丁image_pad = np.pad(image, pad_width=npad, mode='constant', constant_values = 0)# 遍历所有体数据for x in range(PS, image.shape[0]): for y in range(PS, image.shape[1]): for z in range(PS, image.shape[2]): # 将补丁添加到数组中 Patch_array = np.append(Patch_array, image_pad[x-PS:x+PS+1,y-PS:y+PS+1,z-PS:z+PS+1]) Label_array = np.append(Label_array, labels[x,y,z])return Label_array, Patch_array
谢谢!
回答:
Scikit-Image有一个用于此目的的实用函数:
http://scikit-image.org/docs/dev/api/skimage.util.html#view-as-windows
例如:
from skimage.util.shape import view_as_windowswindow_shape = (patch_size, patch_size, patch_size)patch_array = view_as_windows(A, window_shape)
在底层,这使用了numpy.lib.stride_tricks
中的as_strided
函数。