def inference(network, moda_1, moda_g, imageNames, epoch, folder_save): '''root_dir = './Data/MRBrainS/DataNii/' model_dir = 'model' moda_1 = root_dir + 'Training/T1' moda_g = root_dir + 'Training/GT''' network.eval() softMax = nn.Softmax() numClasses = 4 # Move this out if torch.cuda.is_available(): softMax.cuda() network.cuda() dscAll = np.zeros( (len(imageNames), numClasses - 1)) # 1 class is the background!! for i_s in range(len(imageNames)): patch_1, patch_g, img_shape = load_data_test( moda_1, moda_g, imageNames[i_s] ) # hardcoded to read the first file. Loop this to get all files patchSize = 27 patchSize_gt = 9 x = np.zeros((0, 3, patchSize, patchSize, patchSize)) x = np.vstack( (x, np.zeros( (patch_1.shape[0], 3, patchSize, patchSize, patchSize)))) x[:, 0, :, :, :] = patch_1 pred_numpy = np.zeros( (0, numClasses, patchSize_gt, patchSize_gt, patchSize_gt)) pred_numpy = np.vstack( (pred_numpy, np.zeros((patch_1.shape[0], numClasses, patchSize_gt, patchSize_gt, patchSize_gt)))) totalOp = len(imageNames) * patch_1.shape[0] #pred = network(numpy_to_var(x[0,:,:,:,:]).view(1,3,patchSize,patchSize,patchSize)) for i_p in range(patch_1.shape[0]): pred = network( numpy_to_var(x[i_p, :, :, :, :].reshape( 1, 3, patchSize, patchSize, patchSize))) pred_y = softMax(pred) pred_numpy[i_p, :, :, :, :] = pred_y.cpu().data.numpy() printProgressBar(i_s * ((totalOp + 0.0) / len(imageNames)) + i_p + 1, totalOp, prefix="[Validation] ", length=15) # To reconstruct the predicted volume extraction_step_value = 9 pred_classes = np.argmax(pred_numpy, axis=1) pred_classes = pred_classes.reshape( (len(pred_classes), patchSize_gt, patchSize_gt, patchSize_gt)) bin_seg = my_reconstruct_volume( pred_classes, (img_shape[1], img_shape[2], img_shape[3]), patch_shape=(27, 27, 27), extraction_step=(extraction_step_value, extraction_step_value, extraction_step_value)) bin_seg = bin_seg[:, :, extraction_step_value:img_shape[3] - extraction_step_value] gt = nib.load(moda_g + '/' + imageNames[i_s]).get_data() img_pred = nib.Nifti1Image(bin_seg, np.eye(4)) img_gt = nib.Nifti1Image(gt, np.eye(4)) img_name = imageNames[i_s].split('.nii') name = 'Pred_' + img_name[0] + '_Epoch_' + str(epoch) + '.nii.gz' namegt = 'GT_' + img_name[0] + '_Epoch_' + str(epoch) + '.nii.gz' if not os.path.exists(folder_save + 'Segmentations/'): os.makedirs(folder_save + 'Segmentations/') if not os.path.exists(folder_save + 'GT/'): os.makedirs(folder_save + 'GT/') nib.save(img_pred, folder_save + 'Segmentations/' + name) nib.save(img_gt, folder_save + 'GT/' + namegt) dsc = evaluateSegmentation(gt, bin_seg) dscAll[i_s, :] = dsc return dscAll
def inference(network, moda_n, moda_g, imageNames, epoch, folder_save, number_modalities): a = 64 b = 64 '''root_dir = './Data/MRBrainS/DataNii/' model_dir = 'model' moda_1 = root_dir + 'Training/T1' moda_2 = root_dir + 'Training/T1_IR' moda_3 = root_dir + 'Training/T2_FLAIR' moda_g = root_dir + 'Training/GT''' network.eval() softMax = nn.Sigmoid() numClasses = 1 if torch.cuda.is_available(): softMax.cuda() network.cuda() dscAll = [] accall = [] for i_s in range(len(imageNames)): if number_modalities == 2: patch_1, patch_2, patch_g, img_shape = load_data_test( moda_n, moda_g, imageNames[i_s], number_modalities ) # hardcoded to read the first file. Loop this to get all files if number_modalities == 3: patch_1, patch_2, patch_3, patch_g, img_shape = load_data_test( [moda_n], moda_g, imageNames[i_s], number_modalities ) # hardcoded to read the first file. Loop this to get all files # Normalization patchSize = a patchSize_gt = b x = np.zeros((0, number_modalities, patchSize, patchSize, patchSize)) x = np.vstack((x, np.zeros((patch_1.shape[0], number_modalities, patchSize, patchSize, patchSize)))) x[:, 0, :, :, :] = patch_1 x[:, 1, :, :, :] = patch_2 if (number_modalities == 3): x[:, 2, :, :, :] = patch_3 pred_numpy = np.zeros((0, patchSize_gt, patchSize_gt, patchSize_gt)) pred_numpy = np.vstack((pred_numpy, np.zeros((patch_1.shape[0], patchSize_gt, patchSize_gt, patchSize_gt)))) totalOp = len(imageNames) * patch_1.shape[0] #pred = network(numpy_to_var(x[0,:,:,:,:]).view(1,number_modalities,patchSize,patchSize,patchSize)) for i_p in range(patch_1.shape[0]): pred = network( numpy_to_var(x[i_p, :, :, :, :].reshape( 1, number_modalities, patchSize, patchSize, patchSize))) pred_y = softMax( pred.reshape(patchSize_gt, patchSize_gt, patchSize_gt)) pred_numpy[i_p, :, :, :] = pred_y.cpu().data.numpy() printProgressBar(i_s * ((totalOp + 0.0) / len(imageNames)) + i_p + 1, totalOp, prefix="[Validation] ", length=15) # To reconstruct the predicted volume extraction_step_value = b pred_classes = np.round(pred_numpy) pred_classes = pred_classes.reshape( (patch_1.shape[0], patchSize_gt, patchSize_gt, patchSize_gt)) #bin_seg = reconstruct_volume(pred_classes, (img_shape[1], img_shape[2], img_shape[3])) bin_seg = my_reconstruct_volume( pred_classes, (img_shape[1], img_shape[2], img_shape[3]), patch_shape=(a, a, a), extraction_step=(b, b, b)) #bin_seg = bin_seg[:,:,extraction_step_value:img_shape[3]-extraction_step_value] #label_selector = [slice(None)] + [slice(9, 117) for i in range(3)] gt = nib.load(moda_g + '/' + imageNames[i_s]).get_fdata() gt_patches = extract_patches(gt, (a, a, a), (b, b, b)) #gt_patches = gt_patches[label_selector] img_pred = nib.Nifti1Image(bin_seg, np.eye(4)) img_gt = nib.Nifti1Image(gt, np.eye(4)) img_name = imageNames[i_s].split('.nii') name = 'Pred_' + img_name[0] + '_Epoch_' + str(epoch) + '.nii.gz' namegt = 'GT_' + img_name[0] + '_Epoch_' + str(epoch) + '.nii.gz' if not os.path.exists(folder_save + 'Segmentations/'): os.makedirs(folder_save + 'Segmentations/') if not os.path.exists(folder_save + 'GT/'): os.makedirs(folder_save + 'GT/') nib.save(img_pred, folder_save + 'Segmentations/' + name) nib.save(img_gt, folder_save + 'GT/' + namegt) dsc = dc(gt_patches, pred_classes) acc = accuracy_score(gt_patches.flatten(), pred_classes.flatten()) dscAll.append(dsc) accall.append(acc) return dscAll, accall
def inference(network, moda_n, moda_g, imageNames, epoch, folder_save, number_modalities): '''root_dir = './Data/MRBrainS/DataNii/' model_dir = 'model' moda_1 = root_dir + 'Training/T1' moda_2 = root_dir + 'Training/T1_IR' moda_3 = root_dir + 'Training/T2_FLAIR' moda_g = root_dir + 'Training/GT''' network.eval() softMax = nn.Softmax() numClasses = 4 if torch.cuda.is_available(): softMax.cuda() network.cuda() accAll = np.zeros((len(imageNames), numClasses)) dscAll = np.zeros( (len(imageNames), numClasses - 1)) # 1 class is the background!! for i_s in range(len(imageNames)): x_train, y_train, img_shape = load_data_test(moda_n, moda_g, imageNames, 100, number_modalities) pred_numpy = np.zeros( (0, numClasses, x_train.shape[2], x_train.shape[3])) pred_numpy = np.vstack( (pred_numpy, np.zeros((x_train.shape[0], numClasses, x_train.shape[2], x_train.shape[3])))) totalOp = len(imageNames) * x_train.shape[0] for i_p in range(x_train.shape[0]): pred = network( numpy_to_var(x_train[i_p, :, :, :].reshape( 1, number_modalities, x_train.shape[2], x_train.shape[3]))) # To adapt CE to 3D # LOGITS: #这里没明白 pred_y = softMax(pred) pred_numpy[i_p, :, :, :] = pred_y.cpu().data.numpy() printProgressBar(i_s * ((totalOp + 0.0) / len(imageNames)) + i_p + 1, totalOp, prefix="[Validation] ", length=15) # segmentation_prediction = hdNet(MRIs) # predClass_y = softMax(segmentation_prediction) # # print(predClass_y.shape) # pred_classes = np.argmax(predClass_y.cpu().data.numpy(), axis=1) # pred_classes = pred_classes.reshape((len(pred_classes), x_train.shape[2], x_train.shape[3])) # dsc_train = evaluateSegmentation(Segmentation.cpu().data.numpy(),pred_classes) # metric.addBatch(pred_classes.astype(dtype='int'), Segmentation.cpu().data.numpy().astype(dtype='int')) # acc = metric.classPixelAccuracy() pred_classes = np.argmax(pred_numpy, axis=1) pred_classes = pred_classes.reshape( (len(pred_classes), x_train.shape[2], x_train.shape[3])) dsc = evaluateSegmentation(y_train, pred_classes) dscAll[i_s, :] = dsc metric.addBatch(pred_classes.astype(dtype='int'), y_train.astype(dtype='int')) acc = metric.classPixelAccuracy() accAll[i_s, :] = acc return dscAll, accAll
def numpy_to_var(x): torch_tensor = torch.from_numpy(x).type( torch.FloatTensor) #变成张量,与原矩阵共享内存,因此改变张量也会改变原矩阵 if torch.cuda.is_available(): torch_tensor = torch_tensor.cuda() return Variable(torch_tensor) # def inference(network, moda_n, moda_g, imageNames, epoch, folder_save, number_modalities): '''root_dir = './Data/MRBrainS/DataNii/' model_dir = 'model' moda_1 = root_dir + 'Training/T1' moda_2 = root_dir + 'Training/T1_IR' moda_3 = root_dir + 'Training/T2_FLAIR' moda_g = root_dir + 'Training/GT''' network.eval() softMax = nn.Softmax(dim=0) numClasses = 4 if torch.cuda.is_available(): softMax.cuda() network.cuda() dscAll = np.zeros( (len(imageNames), numClasses - 1)) # 1 class is the background!! for i_s in range(len(imageNames)): # if number_modalities == 2: # patch_1, patch_2, patch_g, img_shape = load_data_test(moda_n, moda_g, imageNames[i_s], number_modalities) # hardcoded to read the first file. Loop this to get all files # if number_modalities == 3: # patch_1, patch_2, patch_3, patch_g, img_shape = load_data_test(moda_n, moda_g, imageNames[i_s], number_modalities) # hardcoded to read the first file. Loop this to get all files # patchSize = 27 # patchSize_gt = 9 # x = np.zeros((0, number_modalities, patchSize, patchSize, patchSize)) # x = np.vstack((x, np.zeros((patch_1.shape[0], number_modalities, patchSize, patchSize, patchSize))))#shape(patch_1.shape[0],, number_modalities, patchSize, patchSize, patchSize) # x[:, 0, :, :, :] = patch_1 # x[:, 1, :, :, :] = patch_2 # if (number_modalities==3): # x[:, 2, :, :, :] = patch_3 # pred = network(numpy_to_var(x[0,:,:,:,:]).view(1,number_modalities,patchSize,patchSize,patchSize)) x_train, y_train, img_shape = load_data_test(moda_n, moda_g, imageNames, 100, number_modalities) pred_numpy = np.zeros( (0, numClasses, x_train.shape[2], x_train.shape[3])) pred_numpy = np.vstack( (pred_numpy, np.zeros((x_train.shape[0], numClasses, x_train.shape[2], x_train.shape[3])))) totalOp = len(imageNames) * x_train.shape[0] for i_p in range(x_train.shape[0]): # a=x_train[i_p,:,:,:] # b=x_train[i_p,:,:,:].reshape(1,number_modalities,x_train.shape[2],x_train.shape[3]) pred = network( numpy_to_var(x_train[i_p, :, :, :].reshape( 1, number_modalities, x_train.shape[2], x_train.shape[3]))) # To adapt CE to 3D # LOGITS: #这里没明白 pred_y = softMax(pred) # print(pred_y.numel()) # pred_y = pred_y.permute(0,2,3,1).contiguous()#permute是pytorch中的高维转置函数,返回的是张量 # pred_y = pred_y.view(pred_y.numel() // numClasses, numClasses)#numel返回数量 pred_numpy[i_p, :, :, :] = pred_y.cpu().data.numpy() printProgressBar(i_s * ((totalOp + 0.0) / len(imageNames)) + i_p + 1, totalOp, prefix="[Validation] ", length=15) # To reconstruct the predicted volume # extraction_step_value = 9 pred_classes = np.argmax(pred_numpy, axis=1) pred_classes = pred_classes.reshape( (len(pred_classes), x_train.shape[2], x_train.shape[3])) pred_classes = pred_classes.transpose(1, 2, 0) gt = nib.load(moda_g + '/' + imageNames[i_s]).get_data() img_pred = nib.Nifti1Image(pred_classes, np.eye(4)) img_gt = nib.Nifti1Image(gt, np.eye(4)) img_name = imageNames[i_s].split('.nii') name = 'Pred_' + img_name[0] + '_Epoch_' + str(epoch) + '.nii.gz' namegt = 'GT_' + img_name[0] + '_Epoch_' + str(epoch) + '.nii.gz' if not os.path.exists(folder_save + 'Segmentations/'): os.makedirs(folder_save + 'Segmentations/') if not os.path.exists(folder_save + 'GT/'): os.makedirs(folder_save + 'GT/') nib.save(img_pred, folder_save + 'Segmentations/' + name) nib.save(img_gt, folder_save + 'GT/' + namegt) y_train = y_train.transpose(1, 2, 0) dsc = evaluateSegmentation(y_train, pred_classes) dscAll[i_s, :] = dsc return dscAll
def inference(network, moda_n, moda_g, imageNames, epoch, folder_save, number_modalities, batch_size, CE_loss): '''root_dir = './Data/MRBrainS/DataNii/' model_dir = 'model' moda_1 = root_dir + 'Training/T1' moda_2 = root_dir + 'Training/T1_IR' moda_3 = root_dir + 'Training/T2_FLAIR' moda_g = root_dir + 'Training/GT''' network.eval() softMax = nn.Softmax() numClasses = 4 if torch.cuda.is_available(): softMax.cuda() network.cuda() accAll = np.zeros((len(imageNames), numClasses)) dscAll = np.zeros( (len(imageNames), numClasses - 1)) # 1 class is the background!! val_loss = 0 for i_s in range(len(imageNames)): x_train, y_train, img_shape = load_data_test(moda_n, moda_g, imageNames, 100, number_modalities) data_transforms = transforms.Compose([ transforms.ToTensor(), ]) image_datasets = CustomNpzFolderLoader(x_train, y_train, data_transforms=data_transforms) dataloaders = DataLoader(image_datasets, batch_size=batch_size, shuffle=False) dataset_sizes = len(image_datasets) pred_numpy = np.zeros( (0, numClasses, x_train.shape[2], x_train.shape[3])) pred_numpy = np.vstack( (pred_numpy, np.zeros((x_train.shape[0], numClasses, x_train.shape[2], x_train.shape[3])))) totalOp = len(imageNames) * x_train.shape[0] running_loss = 0.0 for i_p, (train_data, label) in enumerate(dataloaders): # for i_p in range(x_train.shape[0]): # pred = network(numpy_to_var(x_train[i_p,:,:,:].reshape(1,number_modalities,x_train.shape[2],x_train.shape[3]))) if torch.cuda.is_available(): train_data = train_data.cuda().type(torch.cuda.FloatTensor) pred = network(train_data) # To adapt CE to 3D # LOGITS: #这里没明白 pred_y = softMax(pred) pred_numpy[i_p * batch_size:(i_p + 1) * batch_size, :, :, :] = pred_y.cpu().data.numpy() printProgressBar(i_s * ((totalOp + 0.0) / len(imageNames)) + i_p + 1, totalOp, prefix="[Validation] ", length=15) pred = pred.permute( 0, 2, 3, 1).contiguous() #permute是pytorch中的高维转置函数,返回的是张量 pred = pred.view(pred.numel() // numClasses, numClasses) #numel返回数量 CE_loss_batch = CE_loss(pred, label.view(-1).type(torch.cuda.LongTensor)) running_loss += CE_loss_batch.cpu().data.numpy() val_loss += running_loss / dataset_sizes pred_classes = np.argmax(pred_numpy, axis=1) pred_classes = pred_classes.reshape( (len(pred_classes), x_train.shape[2], x_train.shape[3])) dsc = evaluateSegmentation(y_train, pred_classes) dscAll[i_s, :] = dsc metric.addBatch(pred_classes.astype(dtype='int'), y_train.astype(dtype='int')) acc = metric.classPixelAccuracy() accAll[i_s, :] = acc return np.mean(np.array(dscAll), axis=0), np.mean(np.array(accAll), axis=0), val_loss / len(imageNames)