{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Use Case: Unmatched Instances Input" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Install Dependencies" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "!pip install panoptica auxiliary rich numpy > /dev/null" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If you installed the packages and requirements on your own machine, you can skip this section and start from the import section.\n", "\n", "### Setup Colab environment (optional) \n", "Otherwise you can follow and execute the tutorial on your browser.\n", "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*).\n", "\n", "\n", " \"Open\n", "\n", "\n", "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:\n", "1. Warning: This notebook was not authored by Google. Click on 'Run anyway'.\n", "1. When the installation commands are done, there might be \"Restart runtime\" button at the end of the output. Please, click it.\n", "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**.\n", "All generated file will be created/uploaded to your Google Drive respectively.\n", "\n", "After the first execution of the next cell, you might receive some warnings and notifications, please follow these instructions:\n", " - 'Permit this notebook to access your Google Drive files?' Click on 'Yes', and select your account.\n", " - Google Drive for desktop wants to access your Google Account. Click on 'Allow'.\n", "\n", "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." ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "import sys\n", "\n", "# Check if we are in google colab currently\n", "try:\n", " import google.colab\n", "\n", " colabFlag = True\n", "except ImportError as r:\n", " colabFlag = False\n", "\n", "# Execute certain steps only if we are in a colab environment\n", "if colabFlag:\n", " # Create a folder in your Google Drive\n", " from google.colab import drive\n", "\n", " drive.mount(\"/content/drive\")\n", " # clone repository and set path\n", " !git clone https://github.com/BrainLesion/tutorials.git /content/drive/MyDrive/tutorials\n", " BASE_PATH = \"/content/drive/MyDrive/tutorials/panoptica\"\n", " sys.path.insert(0, BASE_PATH)\n", "\n", "else: # normal jupyter notebook environment\n", " BASE_PATH = \".\" # current working directory would be BraTs-Toolkit anyways if you are not in colab" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Setup Imports" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "No module named 'pandas'\n", "OPTIONAL PACKAGE MISSING\n" ] } ], "source": [ "import numpy as np\n", "from auxiliary.nifti.io import read_nifti\n", "from rich import print as pprint\n", "from panoptica import NaiveThresholdMatching, Panoptica_Evaluator, InputType\n", "from panoptica.utils.segmentation_class import LabelGroup, SegmentationClassGroups" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Load Example Data" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "To demonstrate we use a reference and predicition of spine a segmentation with unmatched instances.\n", "\n", "\n", "![unmatched_instance_figure](figures/unmatched_instance.png)" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(array([ 0, 2, 3, 4, 5, 6, 7, 8, 26, 102, 103, 104, 105,\n", " 106, 107, 108, 202, 203, 204, 205, 206, 207, 208], dtype=uint8),\n", " array([ 0, 3, 4, 5, 6, 7, 8, 9, 26, 103, 104, 105, 106,\n", " 107, 108, 109, 203, 204, 205, 206, 207, 208, 209], dtype=uint8))" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "ref_masks = read_nifti(f\"{BASE_PATH}/spine_seg/unmatched_instance/ref.nii.gz\")\n", "pred_masks = read_nifti(f\"{BASE_PATH}/spine_seg/unmatched_instance/pred.nii.gz\")\n", "\n", "# labels are unmatched instances\n", "pred_masks[pred_masks == 27] = 26 # For later\n", "np.unique(ref_masks), np.unique(pred_masks)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Define Class Groups" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [], "source": [ "# Define (optionally) semantic groups\n", "# This means that only instance within one group can be matched to each other\n", "segmentation_class_groups = SegmentationClassGroups(\n", " {\n", " \"vertebra\": LabelGroup(list(range(1, 11))),\n", " \"ivd\": LabelGroup(list(range(101, 111))),\n", " \"sacrum\": ([26], True),\n", " \"endplate\": LabelGroup(list(range(201, 211))),\n", " }\n", ")\n", "# 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)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Let's do it ourselves!\n", "Panoptica allows you to call everything yourself if you really want to" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "prediction_arr= [ 0 2 3 4 5 6 7 8 26 102 103 104 105 106 107 108 202 204\n", " 206 207 209 210 211]\n", "reference_arr= [ 0 2 3 4 5 6 7 8 26 102 103 104 105 106 107 108 202 203\n", " 204 205 206 207 208]\n" ] } ], "source": [ "# Input are unmatched instances, so lets match em!\n", "from panoptica import Metric\n", "\n", "# This will match based on IoU metric, will only match if instance have a IoU of 0.5 or higher and will not allow multiple predictions to be matched to the same reference\n", "matcher = NaiveThresholdMatching(\n", " matching_metric=Metric.IOU, matching_threshold=0.5, allow_many_to_one=False\n", ")\n", "\n", "# Now we have to do our processing object ourselves\n", "from panoptica import UnmatchedInstancePair\n", "\n", "unmatched_instance_input = UnmatchedInstancePair(pred_masks, ref_masks)\n", "\n", "matched_instance_output = matcher.match_instances(unmatched_instance_input)\n", "print(\"prediction_arr=\", np.unique(matched_instance_output.prediction_arr))\n", "print(\"reference_arr=\", np.unique(matched_instance_output.reference_arr))\n", "\n", "# Based of this, we see that some references are not sucessfully hit (203, 205, 208)\n", "# We can also see that we indeed have the same number of prediction instances that got no match, they will be appended afterwards (209, 210, 211)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Let's match 'em all!" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "prediction_arr= [ 0 2 3 4 5 6 7 8 26 102 103 104 105 106 107 108 202 203\n", " 204 205 206 207 208]\n", "reference_arr= [ 0 2 3 4 5 6 7 8 26 102 103 104 105 106 107 108 202 203\n", " 204 205 206 207 208]\n" ] } ], "source": [ "# This will match based on IoU metric, will only match if instance have a IoU of 0.0 or higher and will not allow multiple predictions to be matched to the same reference\n", "matcher = NaiveThresholdMatching(\n", " matching_metric=Metric.IOU, matching_threshold=0.0, allow_many_to_one=False\n", ")\n", "\n", "matched_instance_output = matcher.match_instances(unmatched_instance_input)\n", "print(\"prediction_arr=\", np.unique(matched_instance_output.prediction_arr))\n", "print(\"reference_arr=\", np.unique(matched_instance_output.reference_arr))\n", "\n", "# With a threshold of 0.0, we ensure that we match as much as possible.\n", "# We see, that contrary to before, instances 203, 205, and 208 are now matched" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Do it yourself\n", "\n", "Now it is up to you to explore the different matching algorithms and the best setup for your project\n", "\n", "Just remember, this setup can have drastic differences in the resulting metrics as well as interpretation of those results. For example, if you always match everything, of course your F1-Score will be 1.0. This becomes meaningless then. Also the choice of metric does matter!" ] } ], "metadata": { "kernelspec": { "display_name": "brainles", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.10.14" } }, "nbformat": 4, "nbformat_minor": 2 }