File size: 6,076 Bytes
99c1aa3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
{
 "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
}