#!/usr/bin/env python # coding: utf-8 # # Use Case: Unmatched Instances Input # ## Install Dependencies # In[10]: get_ipython().system('pip install panoptica auxiliary rich numpy > /dev/null') # If you installed the packages and requirements on your own machine, you can skip this section and start from the import section. # # ### Setup Colab environment (optional) # Otherwise you can follow and execute the tutorial on your browser. # In order to start working on the notebook, click on the following button, this will open this page in the Colab environment and you will be able to execute the code on your own (*Google account required*). # # # Open In Colab # # # Now that you are visualizing the notebook in Colab, run the next cell to install the packages we will use. There are few things you should follow in order to properly set the notebook up: # 1. Warning: This notebook was not authored by Google. Click on 'Run anyway'. # 1. When the installation commands are done, there might be "Restart runtime" button at the end of the output. Please, click it. # If you run the next cell in a Google Colab environment, it will **clone the 'tutorials' repository** in your google drive. This will create a **new folder** called "tutorials" in **your Google Drive**. # All generated file will be created/uploaded to your Google Drive respectively. # # After the first execution of the next cell, you might receive some warnings and notifications, please follow these instructions: # - 'Permit this notebook to access your Google Drive files?' Click on 'Yes', and select your account. # - Google Drive for desktop wants to access your Google Account. Click on 'Allow'. # # Afterwards the "tutorials" folder has been created. You can navigate it through the lefthand panel in Colab. You might also have received an email that informs you about the access on your Google Drive. # In[11]: import sys # Check if we are in google colab currently try: import google.colab colabFlag = True except ImportError as r: colabFlag = False # Execute certain steps only if we are in a colab environment if colabFlag: # Create a folder in your Google Drive from google.colab import drive drive.mount("/content/drive") # clone repository and set path get_ipython().system('git clone https://github.com/BrainLesion/tutorials.git /content/drive/MyDrive/tutorials') BASE_PATH = "/content/drive/MyDrive/tutorials/panoptica" sys.path.insert(0, BASE_PATH) else: # normal jupyter notebook environment BASE_PATH = "." # current working directory would be BraTs-Toolkit anyways if you are not in colab # ## Setup Imports # In[12]: import numpy as np from auxiliary.nifti.io import read_nifti from rich import print as pprint from panoptica import NaiveThresholdMatching, Panoptica_Evaluator, InputType from panoptica.utils.segmentation_class import LabelGroup, SegmentationClassGroups # ## Load Example Data # To demonstrate we use a reference and predicition of spine a segmentation with unmatched instances. # # # ![unmatched_instance_figure](figures/unmatched_instance.png) # In[13]: ref_masks = read_nifti(f"{BASE_PATH}/spine_seg/unmatched_instance/ref.nii.gz") pred_masks = read_nifti(f"{BASE_PATH}/spine_seg/unmatched_instance/pred.nii.gz") # labels are unmatching pred_masks[pred_masks == 27] = 26 # For later np.unique(ref_masks), np.unique(pred_masks) # ## Run Evaluation # In[14]: # Define (optionally) semantic groups # This means that only instance within one group can be matched to each other segmentation_class_groups = SegmentationClassGroups( { "vertebra": LabelGroup(list(range(1, 11))), "ivd": LabelGroup(list(range(101, 111))), "sacrum": ([26], True), "endplate": LabelGroup(list(range(201, 211))), } ) # In this case, the label 26 can only be matched with label 26 (thats why have to ensure above that 26 exists in both masks, otherwise they wouldn't be matched) evaluator = Panoptica_Evaluator( expected_input=InputType.UNMATCHED_INSTANCE, instance_matcher=NaiveThresholdMatching(), # If you want to use segmentation class groups, give it here as argument segmentation_class_groups=segmentation_class_groups, ) # ## Inspect Results # The results object allows access to individual metrics and provides helper methods for further processing # In[ ]: # print all results results = evaluator.evaluate(pred_masks, ref_masks, verbose=False) # The groups will have the names specified above for groupname, result in results.items(): print() print("### Group", groupname) print(result) # In[ ]: # get specific metric, e.g. pq # Now we need to specify group first pprint(f"{results['vertebra'].pq=}") # In[ ]: # get dict for further processing, e.g. for pandas pprint("results dict: ", results["vertebra"].to_dict()) # In[ ]: # To inspect different phases, just use the returned intermediate_steps_data object import numpy as np for groupname, result in results.items(): print() print("### Group", groupname) intermediate_steps_data = result.intermediate_steps_data intermediate_steps_data.original_prediction_arr # yields input prediction array intermediate_steps_data.original_reference_arr # yields input reference array # This works with all phases for i in [InputType.UNMATCHED_INSTANCE, InputType.MATCHED_INSTANCE]: try: print(i) pred = intermediate_steps_data.prediction_arr(i) ref = intermediate_steps_data.reference_arr(i) print( "Prediction array shape =", pred.shape, "unique_values=", np.unique(pred), ) print( "Reference array shape =", ref.shape, "unique_values=", np.unique(ref) ) print() except AssertionError as e: print(e) # This happens because Sacrum class group was set to single_instance, hence the Matching phase is skipped and there is no intermediate result for UNMATCHED_INSTANCE