{ "cells": [ { "cell_type": "code", "execution_count": null, "id": "741c0ad2-1f11-4981-b8d5-3f29e4fccde7", "metadata": {}, "outputs": [], "source": [ "from pathlib import Path\n", "from typing import Any, Dict, Tuple, Union\n", "\n", "import os\n", "import numpy as np\n", "import PIL\n", "import SimpleITK" ] }, { "cell_type": "code", "execution_count": null, "id": "b21ce89f-c656-4137-b27c-8ed352fbd5ed", "metadata": {}, "outputs": [], "source": [ "###########################################\n", "# PARAMETERS TO PLAY WITH\n", "\n", "# Select the patient identification (scalar value between 1 and 45)\n", "patient_id = 1\n", "time_id = \"ED\" # ED or ES" ] }, { "cell_type": "code", "execution_count": null, "id": "840099b2-2cbb-45fa-909c-042ea9ad0173", "metadata": {}, "outputs": [], "source": [ "def sitk_load(filepath: Union[str, Path]) -> Tuple[np.ndarray, Dict[str, Any]]:\n", " \"\"\"Loads an image using SimpleITK and returns the image and its metadata.\n", "\n", " Args:\n", " filepath: Path to the image.\n", "\n", " Returns:\n", " - ([N], H, W), Image array.\n", " - Collection of metadata.\n", " \"\"\"\n", " # Load image and save info\n", " image = SimpleITK.ReadImage(str(filepath))\n", " info = {\"origin\": image.GetOrigin(), \"spacing\": image.GetSpacing(), \"direction\": image.GetDirection()}\n", "\n", " # Extract numpy array from the SimpleITK image object\n", " im_array = np.squeeze(SimpleITK.GetArrayFromImage(image))\n", "\n", " return im_array, info\n" ] }, { "cell_type": "code", "execution_count": null, "id": "a4c0c7fb-374e-4b1a-854a-ca02ecd1651a", "metadata": {}, "outputs": [], "source": [ "# Specify the ultrasound/segmentation pair to be loaded\n", "patient_name = f\"patient{patient_id:02d}\"\n", "patient_dir = Path(f\"../dataset/{patient_name}\")\n", "path_to_bmode_image = patient_dir / f\"{patient_name}_{time_id}.nii.gz\"\n", "path_to_gt_segmentation = patient_dir / f\"{patient_name}_{time_id}_gt.nii.gz\"\n", "\n", "# Call of a specific function that reads the .nii.gz files and gives access to the corresponding images and metadata\n", "bmode, info = sitk_load(path_to_bmode_image)\n", "voxelspacing = info['spacing']\n", "depth, width, height = bmode.shape\n", "gt, info_gt = sitk_load(path_to_gt_segmentation)\n", "voxelspacing_gt = info_gt['spacing']\n" ] }, { "cell_type": "code", "execution_count": null, "id": "cb09f80f-d055-40c0-8847-14d1778db212", "metadata": {}, "outputs": [], "source": [ "# Display the corresponding useful information\n", "print(f\"{type(bmode)=}\")\n", "print(f\"{bmode.dtype=}\")\n", "print(f\"{bmode.shape=}\")\n", "print(f\"{voxelspacing=}\")\n", "print('')\n", "\n", "print(f\"{type(gt)=}\")\n", "print(f\"{gt.dtype=}\")\n", "print(f\"{gt.shape=}\")\n", "print(f\"{voxelspacing_gt=}\")" ] }, { "cell_type": "code", "execution_count": null, "id": "b7c9503a-09f3-4fe7-9412-e0d4900a8455", "metadata": {}, "outputs": [], "source": [ "# Display one Y-slice\n", "\n", "%matplotlib inline\n", "from matplotlib import pyplot as plt\n", "slice_id = width // 2\n", "\n", "px = 1/plt.rcParams['figure.dpi'] # pixel in inches\n", "fig = plt.figure(figsize=(depth*px*1.5, height*px*1.5))\n", "bmode_im = plt.imshow(bmode[:,slice_id,:], cmap='gray',vmin=0,vmax=255)\n", "gt_im = plt.imshow(np.ma.masked_where(gt[:,slice_id,:] == 0, gt[:,slice_id,:]), interpolation='none', cmap='jet', alpha=0.5)\n", "plt.axis(\"off\")\n", "plt.tight_layout()" ] }, { "cell_type": "code", "execution_count": null, "id": "c92aa98e-89dc-485d-84b3-77c47d9bbdae", "metadata": {}, "outputs": [], "source": [ "# Display the set of Y-slices as a sequence \n", "%matplotlib inline\n", "from matplotlib import pyplot as plt\n", "from matplotlib import animation\n", "from IPython.display import HTML\n", "\n", "px = 1/plt.rcParams['figure.dpi'] # pixel in inches\n", "fig = plt.figure(figsize=(depth*px*1.5, height*px*1.5))\n", "bmode_im = plt.imshow(bmode[:,0,:], cmap='gray', vmin=0, vmax=255)\n", "gt_im = plt.imshow(np.ma.masked_where(gt[:,0,:] == 0, gt[:,0,:]), interpolation='none', cmap='jet', alpha=0.5)\n", "plt.axis(\"off\")\n", "plt.tight_layout()\n", "plt.close() # this is required to not display the generated image\n", "\n", "def init():\n", " \"\"\"Function that initializes the first frame of the video\"\"\"\n", " bmode_im.set_data(bmode[:,0,:])\n", " gt_im.set_data(gt[:,0,:])\n", "\n", "def animate(frame_idx):\n", " \"\"\"Callback that fetches the data for subsequent frames.\"\"\"\n", " bmode_im.set_data(bmode[:,frame_idx,:])\n", " gt_im.set_data(np.ma.masked_where(gt[:,frame_idx,:] == 0, gt[:,frame_idx,:]))\n", " return bmode_im, gt_im\n", "\n", "interval = 10000 / width # Adjust delay between frames so that animation lasts 10 seconds\n", "anim = animation.FuncAnimation(fig, animate, init_func=init, frames=len(bmode), interval=interval)\n", "HTML(anim.to_html5_video())\n" ] }, { "cell_type": "code", "execution_count": null, "id": "ff197f38-1095-4304-bebe-14365bdf0663", "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "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.8.13" } }, "nbformat": 4, "nbformat_minor": 5 }