三维医学图像数据扩充:flip and rotate
对于小数据量医学图像进行深度学习使,会由于数据量过小而过拟合。因此我们需要采用数据扩充方法,而flip和rotate又是经常用到的,这里做一个简单的实现。
输入为[batchsize,height, width, channel]。这里是2D医学图像数据增强,我之前应该有写到3D增强,不过2D稍加改动也就可以用于3D。
def random_rotate_brain(image, label): bs = image.shape[0] - 1 angle = np.random.randint(-20, 20) # 设置旋转角度 # print("image:{},label:{}".format(image.shape, label.shape)) channel = [ndimage.rotate(image[bs,:,:, c], angle, order=0, reshape=False) for c in range(image.shape[3])] # 每个通道都做相同的旋转 image[bs,...] = np.stack(channel, axis=-1) chlabel = [ndimage.rotate(label[bs,:,:, c], angle, order=0, reshape=False) for c in range(label.shape[3])] # 如果你不想你预测的结果和标签对不上,标签也要进行同样的旋转 label[bs, ...] = np.stack(chlabel, axis=-1) return image, label def random_rot_flip_brain(image, label): axes = (1,2) # 由于我们需要对height和width做扩充,所以取1,2。如果你输入矩阵第一维就是height和width,那你就需要改动为(0,1) k = np.random.randint(0, 4) image = np.rot90(image, k, axes) label = np.rot90(label, k, axes) # print("k:{},img:{},lab:{}".format(k, image.shape,label.shape)) axis = np.random.randint(1, 3) # 同上,只需对1,2维做扩充 image = np.flip(image, axis=axis).copy() label = np.flip(label, axis=axis).copy() return image, label def RandomGenerator_brain(x, y): image, label =x, y # 不可能全部图像都要做数据扩充吧,设置一个随机数 if random.random() > 0.5: image, label = random_rot_flip_brain(image, label) elif random.random() > 0.5: image, label = random_rotate_brain(image, label) return image, label