diff --git a/notebooks/demo_spp_and_gt.ipynb b/notebooks/demo_spp_and_gt.ipynb new file mode 100644 index 0000000..eb10271 --- /dev/null +++ b/notebooks/demo_spp_and_gt.ipynb @@ -0,0 +1,164 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Segmentation 'superpixelSegmentation' already exists. Skipping segmentation.\n" + ] + }, + { + "name": "stderr", + "output_type": "stream", + "text": [ + "/Users/kharrington/.album/micromamba/envs/nesoi/lib/python3.10/site-packages/morphometrics_engine/measure.py:4: TqdmExperimentalWarning: Using `tqdm.autonotebook.tqdm` in notebook mode. Use `tqdm.tqdm` instead to force console mode (e.g. in jupyter console)\n", + " from tqdm.autonotebook import tqdm\n" + ] + } + ], + "source": [ + "import os\n", + "import zarr\n", + "import napari\n", + "import numpy as np\n", + "import copick\n", + "import copick_utils\n", + "from magicgui import magicgui\n", + "from napari.types import ImageData, LabelsData\n", + "from pathlib import Path\n", + "from cellcanvas_spp.segmentation import superpixels\n", + "\n", + "try:\n", + " # DATA_DIR = Path(\"/Users/kharrington/git/cellcanvas/superpixels/notebooks/my_synthetic_data_10439_dataportal.json\")\n", + " DATA_DIR = Path(os.environ[\"COPICK_DATA\"])\n", + "except KeyError:\n", + " raise ValueError(\n", + " \"Please set the COPICK_DATA environment variable to point to the data directory\\n\\n\"\n", + " \"$ export COPICK_DATA=\"\n", + " )\n", + "\n", + "@magicgui(auto_call=True, sigma={\"widget_type\": \"FloatSlider\", \"min\": 0, \"max\": 10}, h_minima={\"widget_type\": \"FloatSlider\", \"min\": 0, \"max\": 50})\n", + "def _spp_widget(image: ImageData, sigma: float = 4, h_minima: float = 0.001) -> LabelsData:\n", + " return superpixels(image, sigma=sigma, h_minima=h_minima)\n", + "\n", + "_spp_widget.h_minima._widget._readout_widget.setDecimals(4)\n", + "\n", + "def get_segmentation_array(copick_run, segmentation_name, voxel_spacing=10, is_multilabel=True):\n", + " seg = copick_run.get_segmentations(is_multilabel=is_multilabel, name=segmentation_name, voxel_size=voxel_spacing)\n", + " if len(seg) == 0:\n", + " return None\n", + " segmentation = zarr.open(seg[0].zarr().path, mode=\"r\")['0']\n", + " return segmentation[:]\n", + "\n", + "def segment_superpixels(example_run, voxel_spacing=10, interactive: bool = False):\n", + " \"\"\"\n", + " This function handles the segmentation logic. If the segmentation exists in copick, it will be skipped.\n", + " \"\"\"\n", + " segmentation_name = \"superpixelSegmentation\"\n", + "\n", + " # Check if the segmentation already exists\n", + " seg = get_segmentation_array(example_run, segmentation_name, voxel_spacing=voxel_spacing, is_multilabel=True)\n", + " if seg is not None:\n", + " print(f\"Segmentation '{segmentation_name}' already exists. Skipping segmentation.\")\n", + " return seg\n", + "\n", + " # Proceed with superpixel segmentation if it does not exist\n", + " tomo_type = \"wbp\"\n", + " tomogram = example_run.voxel_spacings[0].tomograms[0]\n", + "\n", + " # Open zarr\n", + " z = zarr.open(tomogram.zarr())\n", + " img = z[\"0\"] # Get the highest resolution scale\n", + "\n", + " if interactive:\n", + " img = img[50:100, 180:360, 210:430] # Cropping for interactive mode\n", + "\n", + " print(\"Loading image into memory ...\")\n", + " img = np.asarray(img) # Loading into memory\n", + "\n", + " print(\"Segmenting superpixels ...\")\n", + " segm = superpixels(img, sigma=4, h_minima=0.0025)\n", + " print(\"Done ...\")\n", + "\n", + " # Save segmentation into copick\n", + " print(\"Saving segmentation to copick...\")\n", + " new_seg = example_run.new_segmentation(voxel_spacing, segmentation_name, session_id=\"0\", is_multilabel=True, user_id=\"cellcanvasSPP\")\n", + " segmentation_group = zarr.open_group(new_seg.path, mode=\"a\")\n", + " segmentation_group[\"0\"] = segm\n", + " print(\"Segmentation saved.\")\n", + "\n", + " return segm\n", + "\n", + "def prepare_and_run_segmentation(interactive: bool = False):\n", + " \"\"\"\n", + " Prepare and run the segmentation by fetching data from copick.\n", + " \"\"\"\n", + " config_file = DATA_DIR\n", + " root = copick.from_file(config_file)\n", + "\n", + " run_name = \"16193\"\n", + " example_run = root.get_run(run_name)\n", + " voxel_spacing = 10\n", + "\n", + " # Check for existing segmentation or run segmentation if not found\n", + " seg = segment_superpixels(example_run, voxel_spacing, interactive)\n", + "\n", + " # Open viewer and add image\n", + " viewer = napari.Viewer()\n", + " img = np.asarray(zarr.open(example_run.voxel_spacings[0].tomograms[0].zarr())[\"0\"]) # Load image\n", + " viewer.add_image(img)\n", + " viewer.add_labels(seg, name=\"Superpixels\")\n", + "\n", + " # Add ground truth\n", + " base_seg = np.zeros_like(zarr.open(example_run.segmentations[0].zarr())[\"0\"])\n", + " for idx, seg in enumerate(example_run.segmentations):\n", + " z = zarr.open(seg.zarr())[\"0\"][:]\n", + " base_seg = base_seg + (idx + 1) * z\n", + " viewer.add_labels(base_seg)\n", + "\n", + " # If interactive mode, show the widget\n", + " if interactive:\n", + " viewer.window.add_dock_widget(_spp_widget, area=\"right\")\n", + "\n", + " # napari.run()\n", + " return viewer\n", + "\n", + "# Run segmentation directly in a Jupyter notebook\n", + "viewer = prepare_and_run_segmentation(interactive=False)\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "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.8" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +}