def init_evaluator() -> eval_.Evaluator: """Initializes an evaluator. Args: directory (str): The directory for the results file. result_file_name (str): The result file name (CSV file). Returns: eval.Evaluator: An evaluator. """ # os.makedirs(directory, exist_ok=True) # generate result directory, if it does not exists # evaluator = eval_.Evaluator(eval_.ConsoleEvaluatorWriter(5)) evaluation_metrics = [metric.DiceCoefficient(), metric.HausdorffDistance()] # evaluation_metrics = [metric.DiceCoefficient(), metric.HausdorffDistance(), metric.Accuracy(), metric.CohenKappaCoefficient(), metric.ProbabilisticDistance()] evaluation_metrics = [metric.DiceCoefficient(), metric.HausdorffDistance(95), metric.CohenKappaCoefficient(), metric.Accuracy(), metric.JaccardCoefficient(), metric.MutualInformation(), metric.Precision(), metric.VolumeSimilarity(), metric.AreaUnderCurve(), metric.FalseNegative(),metric.FalsePositive(), metric.TruePositive(), metric.TrueNegative(),metric.Sensitivity(),metric.Specificity()] evaluation_metrics=[metric.DiceCoefficient(),metric.JaccardCoefficient(),metric.SurfaceDiceOverlap(),metric.Accuracy(), metric.FMeasure(),metric.CohenKappaCoefficient(),metric.VolumeSimilarity(),metric.MutualInformation(),metric.AreaUnderCurve(), metric.HausdorffDistance()] evaluator = eval_.SegmentationEvaluator(evaluation_metrics,{}) # evaluator.add_writer(eval_.CSVEvaluatorWriter(os.path.join(directory, result_file_name))) evaluator.add_label(1, 'WhiteMatter') evaluator.add_label(2, 'GreyMatter') evaluator.add_label(3, 'Hippocampus') evaluator.add_label(4, 'Amygdala') evaluator.add_label(5, 'Thalamus') # warnings.warn('Initialized evaluation with the Dice coefficient. Do you know other suitable metrics?') # you should add more metrics than just the Hausdorff distance! return evaluator
def init_evaluator(directory: str, result_file_name: str = 'results.csv') -> eval_.Evaluator: """Initializes an evaluator. Args: directory (str): The directory for the results file. result_file_name (str): The result file name (CSV file). Returns: eval.Evaluator: An evaluator. """ os.makedirs( directory, exist_ok=True) # generate result directory, if it does not exists evaluator = eval_.Evaluator(eval_.ConsoleEvaluatorWriter(5)) evaluator.add_writer( eval_.CSVEvaluatorWriter(os.path.join(directory, result_file_name))) evaluator.add_label(1, "WhiteMatter") evaluator.add_label(2, "GreyMatter") evaluator.add_label(3, "Hippocampus") evaluator.add_label(4, "Amygdala") evaluator.add_label(5, "Thalamus") evaluator.add_metric(metric.DiceCoefficient()) evaluator.add_metric(metric.Specificity()) evaluator.add_metric(metric.Sensitivity()) evaluator.add_metric(metric.HausdorffDistance()) return evaluator
def init_evaluator(directory: str, result_file_name: str = 'results.csv') -> eval_.Evaluator: """Initializes an evaluator. Args: directory (str): The directory for the results file. result_file_name (str): The result file name (CSV file). Returns: eval.Evaluator: An evaluator. """ os.makedirs( directory, exist_ok=True) # generate result directory, if it does not exists evaluator = eval_.Evaluator(eval_.ConsoleEvaluatorWriter(5)) evaluator.add_writer( eval_.CSVEvaluatorWriter(os.path.join(directory, result_file_name))) evaluator.add_label(1, 'WhiteMatter') evaluator.add_label(2, 'GreyMatter') evaluator.add_label(3, 'Hippocampus') evaluator.add_label(4, 'Amygdala') evaluator.add_label(5, 'Thalamus') evaluator.metrics = [ metric.DiceCoefficient(), metric.HausdorffDistance(95) ] # Solutions # todo: add hausdorff distance, 95th percentile (see metric.HausdorffDistance) # evaluator.add_metric(metric.HausdorffDistance(95)) # warnings.warn('Initialized evaluation with the Dice coefficient. Do you know other suitable metrics?') return evaluator
def main(data_dir: str, result_file: str, result_summary_file: str): # initialize metrics metrics = [ metric.DiceCoefficient(), metric.HausdorffDistance(percentile=95, metric='HDRFDST95'), metric.VolumeSimilarity() ] # define the labels to evaluate labels = {1: 'WHITEMATTER', 2: 'GREYMATTER', 5: 'THALAMUS'} evaluator = eval_.SegmentationEvaluator(metrics, labels) # get subjects to evaluate subject_dirs = [ subject for subject in glob.glob(os.path.join(data_dir, '*')) if os.path.isdir(subject) and os.path.basename(subject).startswith('Subject') ] for subject_dir in subject_dirs: subject_id = os.path.basename(subject_dir) print(f'Evaluating {subject_id}...') # load ground truth image and create artificial prediction by erosion ground_truth = sitk.ReadImage( os.path.join(subject_dir, f'{subject_id}_GT.mha')) prediction = ground_truth for label_val in labels.keys(): # erode each label we are going to evaluate prediction = sitk.BinaryErode(prediction, 1, sitk.sitkBall, 0, label_val) # evaluate the "prediction" against the ground truth evaluator.evaluate(prediction, ground_truth, subject_id) # use two writers to report the results writer.CSVWriter(result_file).write(evaluator.results) print('\nSubject-wise results...') writer.ConsoleWriter().write(evaluator.results) # report also mean and standard deviation among all subjects functions = {'MEAN': np.mean, 'STD': np.std} writer.CSVStatisticsWriter(result_summary_file, functions=functions).write(evaluator.results) print('\nAggregated statistic results...') writer.ConsoleStatisticsWriter(functions=functions).write( evaluator.results) # clear results such that the evaluator is ready for the next evaluation evaluator.clear()
def init_evaluator(write_to_console: bool = True, csv_file: str = None, calculate_distance_metrics: bool = False): evaluator = eval.Evaluator(EvaluatorAggregator()) if write_to_console: evaluator.add_writer(eval.ConsoleEvaluatorWriter(5)) if csv_file is not None: evaluator.add_writer(eval.CSVEvaluatorWriter(csv_file)) if calculate_distance_metrics: evaluator.metrics = [ pymia_metric.DiceCoefficient(), pymia_metric.HausdorffDistance(), pymia_metric.HausdorffDistance(percentile=95, metric='HDRFDST95'), pymia_metric.VolumeSimilarity() ] else: evaluator.metrics = [ pymia_metric.DiceCoefficient(), pymia_metric.VolumeSimilarity() ] evaluator.add_label(1, cfg.FOREGROUND_NAME) return evaluator
def init_evaluator() -> eval_.Evaluator: """Initializes an evaluator. Returns: eval.Evaluator: An evaluator. """ # initialize metrics metrics = [metric.DiceCoefficient(), metric.HausdorffDistance(95.0)] # define the labels to evaluate labels = { 1: 'WhiteMatter', 2: 'GreyMatter', 3: 'Hippocampus', 4: 'Amygdala', 5: 'Thalamus' } evaluator = eval_.SegmentationEvaluator(metrics, labels) return evaluator
def init_evaluator() -> eval_.Evaluator: """Initializes an evaluator. Returns: eval.Evaluator: An evaluator. """ # initialize metrics metrics = [metric.DiceCoefficient(), metric.HausdorffDistance(percentile=95)] # todo: add hausdorff distance, 95th percentile (see metric.HausdorffDistance) # warnings.warn('Initialized evaluation with the Dice coefficient. Do you know other suitable metrics?') # define the labels to evaluate labels = {1: 'WhiteMatter', 2: 'GreyMatter', 3: 'Hippocampus', 4: 'Amygdala', 5: 'Thalamus' } evaluator = eval_.SegmentationEvaluator(metrics, labels) return evaluator
def init_evaluator(directory: object, result_file_name: object = 'results.csv') -> object: """Initializes an evaluator. Args: directory (str): The directory for the results file. result_file_name (str): The result file name (CSV file). Returns: eval.Evaluator: An evaluator. """ os.makedirs(directory, exist_ok=True) # generate result directory, if it does not exists evaluator = eval_.Evaluator(eval_.ConsoleEvaluatorWriter(5)) evaluator.add_writer(eval_.CSVEvaluatorWriter(os.path.join(directory, result_file_name))) evaluator.add_label(1, 'WhiteMatter') evaluator.add_label(2, 'GreyMatter') evaluator.add_label(3, 'Hippocampus') evaluator.add_label(4, 'Amygdala') evaluator.add_label(5, 'Thalamus') evaluator.metrics = [metric.DiceCoefficient(), metric.HausdorffDistance()] # warnings.warn('Initialized evaluation with the Dice coefficient. Do you know other suitable metrics?') # you should add more metrics than just the Hausdorff distance! return evaluator
def load_atlas_custom_images(wdpath): # params_list = list(data_batch.items()) # print(params_list[0] ) t1w_list = [] t2w_list = [] gt_label_list = [] brain_mask_list = [] transform_list = [] #Load the train labels_native with their transform for dirpath, subdirs, files in os.walk(wdpath): # print("dirpath", dirpath) # print("subdirs", subdirs) # print("files", files) for x in files: if x.endswith("T1native.nii.gz"): t1w_list.append(sitk.ReadImage(os.path.join(dirpath, x))) elif x.endswith("T2native.nii.gz"): t2w_list.append(sitk.ReadImage(os.path.join(dirpath, x))) elif x.endswith("labels_native.nii.gz"): gt_label_list.append(sitk.ReadImage(os.path.join(dirpath, x))) elif x.endswith("Brainmasknative.nii.gz"): brain_mask_list.append(sitk.ReadImage(os.path.join(dirpath, x))) elif x.endswith("affine.txt"): transform_list.append( sitk.ReadTransform(os.path.join(dirpath, x))) # else: # print("Problem in CustomAtlas in folder", dirpath) #Resample and thershold to get the label white_matter_list = [] grey_matter_list = [] hippocampus_list = [] amygdala_list = [] thalamus_list = [] for i in range(0, len(gt_label_list)): resample_img = sitk.Resample(gt_label_list[i], atlas_t1, transform_list[i], sitk.sitkNearestNeighbor, 0, gt_label_list[i].GetPixelIDValue()) white_matter_list.append(sitk.Threshold(resample_img, 1, 1, 0)) grey_matter_list.append(sitk.Threshold(resample_img, 2, 2, 0)) hippocampus_list.append(sitk.Threshold(resample_img, 3, 3, 0)) amygdala_list.append(sitk.Threshold(resample_img, 4, 4, 0)) thalamus_list.append(sitk.Threshold(resample_img, 5, 5, 0)) #Save each label from first data path_to_save = '../bin/custom_atlas_result/' if not os.path.exists(path_to_save): os.makedirs(path_to_save) sitk.WriteImage(hippocampus_list[0], os.path.join(path_to_save, 'Hippocampus_label.nii'), True) sitk.WriteImage(white_matter_list[0], os.path.join(path_to_save, 'White_matter_label.nii'), True) sitk.WriteImage(grey_matter_list[0], os.path.join(path_to_save, 'Grey_matter_label.nii'), True) sitk.WriteImage(amygdala_list[0], os.path.join(path_to_save, 'Amygdala_label.nii'), True) sitk.WriteImage(thalamus_list[0], os.path.join(path_to_save, 'Thalamus_label.nii'), True) #Save an image resampled to show segmentation sitk.WriteImage(gt_label_list[0], os.path.join(path_to_save, 'Train_image_1_resampled.nii'), True) # sum them up and divide by their number of images to make a probability map white_matter_map = 0 grey_matter_map = 0 hippocampus_map = 0 amygdala_map = 0 thalamus_map = 0 for i in range(1, len(gt_label_list)): white_matter_map = sitk.Add(white_matter_map, white_matter_list[i]) grey_matter_map = sitk.Add(grey_matter_map, grey_matter_list[i]) hippocampus_map = sitk.Add(hippocampus_map, hippocampus_list[i]) amygdala_map = sitk.Add(amygdala_map, amygdala_list[i]) thalamus_map = sitk.Add(thalamus_map, thalamus_list[i]) white_matter_map = sitk.Divide(white_matter_map, len(white_matter_list)) grey_matter_map = sitk.Divide(grey_matter_map, len(grey_matter_list)) hippocampus_map = sitk.Divide(hippocampus_map, len(hippocampus_list)) amygdala_map = sitk.Divide(amygdala_map, len(amygdala_list)) thalamus_map = sitk.Divide(thalamus_map, len(thalamus_list)) #atlas = sitk.Divide(sum_images, len(test_resample)) #slice = sitk.GetArrayFromImage(atlas)[90,:,:] #plt.imshow(slice) #Register without threshold path_to_save = '../bin/custom_atlas_result/' if not os.path.exists(path_to_save): os.makedirs(path_to_save) sitk.WriteImage( grey_matter_map, os.path.join(path_to_save, 'grey_matter_map_no_threshold.nii'), True) sitk.WriteImage( white_matter_map, os.path.join(path_to_save, 'white_matter_map_no_threshold.nii'), True) sitk.WriteImage( hippocampus_map, os.path.join(path_to_save, 'hippocampus_map_no_threshold.nii'), True) sitk.WriteImage( amygdala_map, os.path.join(path_to_save, 'amygdala_map_no_threshold.nii'), True) sitk.WriteImage( thalamus_map, os.path.join(path_to_save, 'thalamus_map_no_threshold.nii'), True) #Threhold the 5 different maps to get a binary map white_matter_map = sitk.BinaryThreshold(white_matter_map, 0.3, 1, 1, 0) grey_matter_map = sitk.BinaryThreshold(grey_matter_map, 0.6, 2, 2, 0) hippocampus_map = sitk.BinaryThreshold(hippocampus_map, 0.9, 3, 3, 0) amygdala_map = sitk.BinaryThreshold(amygdala_map, 1.2, 4, 4, 0) thalamus_map = sitk.BinaryThreshold(thalamus_map, 1.5, 5, 5, 0) #Save the images path_to_save = '../bin/custom_atlas_result/' if not os.path.exists(path_to_save): os.makedirs(path_to_save) sitk.WriteImage(grey_matter_map, os.path.join(path_to_save, 'grey_matter_map.nii'), True) sitk.WriteImage(white_matter_map, os.path.join(path_to_save, 'white_matter_map.nii'), True) sitk.WriteImage(hippocampus_map, os.path.join(path_to_save, 'hippocampus_map.nii'), True) sitk.WriteImage(amygdala_map, os.path.join(path_to_save, 'amygdala_map.nii'), True) sitk.WriteImage(thalamus_map, os.path.join(path_to_save, 'thalamus_map.nii'), True) # Load the test labels_native and their transform path_to_test = '../data/test' test_gt_label_list = [] test_transform_list = [] for dirpath, subdirs, files in os.walk(path_to_test): for x in files: if x.endswith("labels_native.nii.gz"): test_gt_label_list.append( sitk.ReadImage(os.path.join(dirpath, x))) if x.endswith("affine.txt"): test_transform_list.append( sitk.ReadTransform(os.path.join(dirpath, x))) #Resample the labels_native with the transform test_resample_img = [] for i in range(0, len(test_gt_label_list)): resample_img = sitk.Resample(test_gt_label_list[i], atlas_t1, test_transform_list[i], sitk.sitkNearestNeighbor, 0, test_gt_label_list[i].GetPixelIDValue()) test_resample_img.append(resample_img) sitk.WriteImage(test_resample_img[0], os.path.join(path_to_save, 'Test_data_1_resampled.nii'), True) # Save the first test patient labels # path_to_save = '../bin/temp_test_result/' # if not os.path.exists(path_to_save): # os.makedirs(path_to_save) # sitk.WriteImage(test_resample_img[0], os.path.join(path_to_save, 'FirstPatienFromTestList.nii'), False) #Compute the dice coeefficent (and the Hausdorff distance) label_list = [ 'White Matter', 'Grey Matter', 'Hippocampus', 'Amygdala', 'Thalamus' ] map_list = [ white_matter_map, grey_matter_map, hippocampus_map, amygdala_map, thalamus_map ] dice_list = [] path_to_save = '../bin/DiceTestResult/' if not os.path.exists(path_to_save): os.makedirs(path_to_save) for i in range(0, 5): evaluator = eval_.Evaluator(eval_.ConsoleEvaluatorWriter(5)) evaluator.metrics = [ metric.DiceCoefficient(), metric.HausdorffDistance() ] evaluator.add_writer( eval_.CSVEvaluatorWriter( os.path.join(path_to_save, 'DiceResults_' + label_list[i] + '.csv'))) evaluator.add_label(i + 1, label_list[i]) for j in range(0, len(test_resample_img)): evaluator.evaluate(test_resample_img[j], map_list[i], 'Patient ' + str(j)) print("END Custom loadAtlas")