{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "Automatic estimation of Ejection Fraction from echocardiographic images using the Simpson's biplane method of disks\n", "===\n", "\n", "***\n", "# Preamble\n", "\n", "This notebook provides a method to compute the ejection fraction from Simpson's biplane method of disks using the segmentation obtained from 2D echocardiographic images at end diastole and end systole time instances from Apical two and four chambers views. This method was used in the following paper:\n", "\n", "Leclerc S, Smistad E, Pedrosa J, Østvik A, Cervenansky F, Espinosa F, Espeland T, Rye Berg EA, Jodoin PM, Grenier T, Lartizien C, D’hooge J, Lovstakken L, Bernard O. \"Deep Learning for Segmentation using an Open Large-Scale Dataset in 2D Echocardiography\" IEEE Trans Med Imaging, 2019:38:2198-2210, DOI: 10.1109/TMI.2019.2900516\n", " \n", "# Objectives\n", "\n", "* Provide the code to compute EF for open science purposes \n", "* This code can be run from the [CAMUS dataset](https://humanheart-project.creatis.insa-lyon.fr/database/#collection/6373703d73e9f0047faa1bc8) to reproduce the EF values provided in this collection\n", " \n", "***\n", "\n", "# Warnings\n", "\n", "* We have observed that the way in which Simpson's biplane method is implemented can have a significant influence on the final values calculated. We do not guarantee that the method implemented in this notebook is optimal. The values produced by this method should be used with caution.\n", " " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Import the different python librairies" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "tags": [] }, "outputs": [], "source": [ "import logging\n", "from pathlib import Path\n", "from typing import Any, Dict, Tuple\n", "\n", "import numpy as np\n", "import PIL\n", "import SimpleITK as sitk\n", "from PIL.Image import Resampling\n", "from skimage.measure import find_contours\n", "\n", "logger = logging.getLogger(__name__)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Let's define a few useful functions to load and manipulate images" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "is_executing": true, "tags": [] }, "outputs": [], "source": [ "def sitk_load(filepath: 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 = sitk.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(sitk.GetArrayFromImage(image))\n", "\n", " return im_array, info" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "tags": [] }, "outputs": [], "source": [ "def resize_image(image: np.ndarray, size: Tuple[int, int], resample: Resampling = Resampling.NEAREST) -> np.ndarray:\n", " \"\"\"Resizes the image to the specified dimensions.\n", "\n", " Args:\n", " image: (H, W), Input image to resize. Must be in a format supported by PIL.\n", " size: Width (W') and height (H') dimensions of the resized image to output.\n", " resample: Resampling filter to use.\n", "\n", " Returns:\n", " (H', W'), Input image resized to the specified dimensions.\n", " \"\"\"\n", " resized_image = np.array(PIL.Image.fromarray(image).resize(size, resample=resample))\n", " return resized_image" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "tags": [] }, "outputs": [], "source": [ "def resize_image_to_isotropic(\n", " image: np.ndarray, spacing: Tuple[float, float], resample: Resampling = Resampling.NEAREST\n", ") -> np.ndarray:\n", " \"\"\"Resizes the image to attain isotropic spacing, by resampling the dimension with the biggest voxel size.\n", "\n", " Args:\n", " image: (H, W), Input image to resize. Must be in a format supported by PIL.\n", " spacing: Size of the image's pixels along each (height, width) dimension.\n", " resample: Resampling filter to use.\n", "\n", " Returns:\n", " (H', W'), Input image resized so that the spacing is isotropic, and the isotropic value of the new spacing.\n", " \"\"\"\n", " scaling = np.array(spacing) / min(spacing)\n", " new_height, new_width = (np.array(image.shape) * scaling).round().astype(int)\n", " return resize_image(image, (new_width, new_height), resample=resample), min(spacing)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Implement Simpson's biplane method of disks" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "tags": [] }, "outputs": [], "source": [ "def compute_left_ventricle_volumes(\n", " a2c_ed: np.ndarray,\n", " a2c_es: np.ndarray,\n", " a2c_voxelspacing: Tuple[float, float],\n", " a4c_ed: np.ndarray,\n", " a4c_es: np.ndarray,\n", " a4c_voxelspacing: Tuple[float, float],\n", ") -> Tuple[float, float]:\n", " \"\"\"Computes the ED and ES volumes of the left ventricle from 2 orthogonal 2D views (A2C and A4C).\n", "\n", " Args:\n", " a2c_ed: (H,W), Binary segmentation map of the left ventricle from the end-diastole (ED) instant of the 2-chamber\n", " apical view (A2C).\n", " a2c_es: (H,W), Binary segmentation map of the left ventricle from the end-systole (ES) instant of the 2-chamber\n", " apical view (A2C).\n", " a2c_voxelspacing: Size (in mm) of the 2-chamber apical view's voxels along each (height, width) dimension.\n", " a4c_ed: (H,W), Binary segmentation map of the left ventricle from the end-diastole (ED) instant of the 4-chamber\n", " apical view (A4C).\n", " a4c_es: (H,W), Binary segmentation map of the left ventricle from the end-systole (ES) instant of the 4-chamber\n", " apical view (A4C).\n", " a4c_voxelspacing: Size (in mm) of the 4-chamber apical view's voxels along each (height, width) dimension.\n", "\n", " Returns:\n", " Left ventricle ED and ES volumes.\n", " \"\"\"\n", " for mask_name, mask in [(\"a2c_ed\", a2c_ed), (\"a2c_es\", a2c_es), (\"a4c_ed\", a4c_ed), (\"a4c_es\", a4c_es)]:\n", " if mask.max() > 1:\n", " logger.warning(\n", " f\"`compute_left_ventricle_volumes` expects binary segmentation masks of the left ventricle (LV). \"\n", " f\"However, the `{mask_name}` segmentation contains a label greater than '1/True'. If this was done \"\n", " f\"voluntarily, you can safely ignore this warning. However, the most likely cause is that you forgot \"\n", " f\"to extract the binary LV segmentation from a multi-class segmentation mask.\"\n", " )\n", "\n", " a2c_ed_diameters, a2c_ed_step_size = _compute_diameters(a2c_ed, a2c_voxelspacing)\n", " a2c_es_diameters, a2c_es_step_size = _compute_diameters(a2c_es, a2c_voxelspacing)\n", " a4c_ed_diameters, a4c_ed_step_size = _compute_diameters(a4c_ed, a4c_voxelspacing)\n", " a4c_es_diameters, a4c_es_step_size = _compute_diameters(a4c_es, a4c_voxelspacing)\n", " step_size = max((a2c_ed_step_size, a2c_es_step_size, a4c_ed_step_size, a4c_es_step_size))\n", "\n", " ed_volume = _compute_left_ventricle_volume_by_instant(a2c_ed_diameters, a4c_ed_diameters, step_size)\n", " es_volume = _compute_left_ventricle_volume_by_instant(a2c_es_diameters, a4c_es_diameters, step_size)\n", " return ed_volume, es_volume\n", "\n", "\n", "def _compute_left_ventricle_volume_by_instant(\n", " a2c_diameters: np.ndarray, a4c_diameters: np.ndarray, step_size: float\n", ") -> float:\n", " \"\"\"Compute left ventricle volume using Biplane Simpson's method.\n", "\n", " Args:\n", " a2c_diameters: Diameters measured at each key instant of the cardiac cycle, from the 2-chamber apical view.\n", " a4c_diameters: Diameters measured at each key instant of the cardiac cycle, from the 4-chamber apical view.\n", " step_size:\n", "\n", " Returns:\n", " Left ventricle volume (in millilitres).\n", " \"\"\"\n", " # All measures are now in millimeters, convert to meters by dividing by 1000\n", " a2c_diameters /= 1000\n", " a4c_diameters /= 1000\n", " step_size /= 1000\n", "\n", " # Estimate left ventricle volume from orthogonal disks\n", " lv_volume = np.sum(a2c_diameters * a4c_diameters) * step_size * np.pi / 4\n", "\n", " # Volume is now in cubic meters, so convert to milliliters (1 cubic meter = 1_000_000 milliliters)\n", " return round(lv_volume * 1e6)\n", "\n", "\n", "def _find_distance_to_edge(\n", " segmentation: np.ndarray, point_on_mid_line: np.ndarray, normal_direction: np.ndarray\n", ") -> float:\n", " distance = 8 # start a bit in to avoid line stopping early at base\n", " while True:\n", " current_position = point_on_mid_line + distance * normal_direction\n", "\n", " y, x = np.round(current_position).astype(int)\n", " if segmentation.shape[0] <= y or y < 0 or segmentation.shape[1] <= x or x < 0:\n", " # out of bounds\n", " return distance\n", "\n", " elif segmentation[y, x] == 0:\n", " # Edge found\n", " return distance\n", "\n", " distance += 0.5\n", "\n", "\n", "def _distance_line_to_points(line_point_0: np.ndarray, line_point_1: np.ndarray, points: np.ndarray) -> np.ndarray:\n", " # https://en.wikipedia.org/wiki/Distance_from_a_point_to_a_line\n", " return np.absolute(np.cross(line_point_1 - line_point_0, line_point_0 - points)) / np.linalg.norm(\n", " line_point_1 - line_point_0\n", " )\n", "\n", "\n", "def _get_angle_of_lines_to_point(reference_point: np.ndarray, moving_points: np.ndarray) -> np.ndarray:\n", " diff = moving_points - reference_point\n", " return abs(np.degrees(np.arctan2(diff[:, 0], diff[:, 1])))\n", "\n", "\n", "def _compute_diameters(segmentation: np.ndarray, voxelspacing: Tuple[float, float]) -> Tuple[np.ndarray, float]:\n", " \"\"\"\n", "\n", " Args:\n", " segmentation: Binary segmentation of the structure for which to find the diameter.\n", " voxelspacing: Size of the segmentations' voxels along each (height, width) dimension (in mm).\n", "\n", " Returns:\n", " \"\"\"\n", "\n", " # Make image isotropic, have same spacing in both directions.\n", " # The spacing can be multiplied by the diameter directly.\n", " segmentation, isotropic_spacing = resize_image_to_isotropic(segmentation, voxelspacing)\n", "\n", " # Go through entire contour to find AV plane\n", " contour = find_contours(segmentation, 0.5)[0]\n", "\n", " # For each pair of contour points\n", " # Check if angle is ok\n", " # If angle is ok, check that almost all other contour points are above the line\n", " # Or check that all points between are close to the line\n", " # If so, it is accepted, select the longest stretch\n", " best_length = 0\n", " for point_idx in range(2, len(contour)):\n", " previous_points = contour[:point_idx]\n", " angles_to_previous_points = _get_angle_of_lines_to_point(contour[point_idx], previous_points)\n", "\n", " for acute_angle_idx in np.nonzero(angles_to_previous_points <= 45)[0]:\n", " intermediate_points = contour[acute_angle_idx + 1 : point_idx]\n", " distance_to_intermediate_points = _distance_line_to_points(\n", " contour[point_idx], contour[acute_angle_idx], intermediate_points\n", " )\n", " if np.all(distance_to_intermediate_points <= 8):\n", " distance = np.linalg.norm(contour[point_idx] - contour[acute_angle_idx])\n", " if best_length < distance:\n", " best_length = distance\n", " best_i = point_idx\n", " best_j = acute_angle_idx\n", "\n", " mid_point = int(best_j + round((best_i - best_j) / 2))\n", " # Apex is longest from midpoint\n", " mid_line_length = 0\n", " apex = 0\n", " for i in range(len(contour)):\n", " length = np.linalg.norm(contour[mid_point] - contour[i])\n", " if mid_line_length < length:\n", " mid_line_length = length\n", " apex = i\n", "\n", " direction = contour[apex] - contour[mid_point]\n", " normal_direction = np.array([-direction[1], direction[0]])\n", " normal_direction = normal_direction / np.linalg.norm(normal_direction) # Normalize\n", " diameters = []\n", " for fraction in np.linspace(0, 1, 20, endpoint=False):\n", " point_on_mid_line = contour[mid_point] + direction * fraction\n", "\n", " distance1 = _find_distance_to_edge(segmentation, point_on_mid_line, normal_direction)\n", " distance2 = _find_distance_to_edge(segmentation, point_on_mid_line, -normal_direction)\n", " diameters.append((distance1 + distance2) * isotropic_spacing)\n", "\n", " step_size = (mid_line_length * isotropic_spacing) / 20\n", " return np.array(diameters), step_size\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Load the 2D segmentation masks required to compute the left ventricular volumes and ejection fraction (EF) for one patient\n", "\n", "NOTE: The following cells assume that the `database_nifti` archive was downloaded and extracted in the current directory." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "tags": [] }, "outputs": [], "source": [ "###########################################\n", "# PARAMETERS TO PLAY WITH\n", "\n", "database_nifti_root = Path(\"../database_nifti\")\n", "lv_label = 1\n", "# Select the patient identification (scalar value between 1 and 500)\n", "patient_id = 1" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "tags": [] }, "outputs": [], "source": [ "print(database_nifti_root)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Specify the ID and path of the patient to be loaded\n", "patient_name = f\"patient{patient_id:04d}\"\n", "patient_dir = database_nifti_root / patient_name\n", "gt_mask_pattern = \"{patient_name}_{view}_{instant}_gt.nii.gz\"\n", "print(f\"Loading data from patient folder: {patient_dir}\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "view = \"2CH\"\n", "instant = \"ED\"\n", "a2c_ed, a2c_info = sitk_load(patient_dir / gt_mask_pattern.format(patient_name=patient_name, view=view, instant=instant))\n", "a2c_voxelspacing = a2c_info[\"spacing\"][:2][::-1] # Extract the (width,height) dimension from the metadata and order them like in the mask" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "instant = \"ES\"\n", "a2c_es, _ = sitk_load(patient_dir / gt_mask_pattern.format(patient_name=patient_name, view=view, instant=instant))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "view = \"4CH\"\n", "instant = \"ED\"\n", "a4c_ed, a4c_info = sitk_load(patient_dir / gt_mask_pattern.format(patient_name=patient_name, view=view, instant=instant))\n", "a4c_voxelspacing = a4c_info[\"spacing\"][:2][::-1] # Extract the (width,height) dimension from the metadata and order them like in the mask" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "instant = \"ES\"\n", "a4c_es, _ = sitk_load(patient_dir / gt_mask_pattern.format(patient_name=patient_name, view=view, instant=instant))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Run Simpson's biplane method of disks on the data from the selected patient" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Extract binary LV masks from the multi-class segmentation masks\n", "a2c_ed_lv_mask = a2c_ed == lv_label\n", "a2c_es_lv_mask = a2c_es == lv_label\n", "a4c_ed_lv_mask = a4c_ed == lv_label\n", "a4c_es_lv_mask = a4c_es == lv_label\n", "\n", "# Use the provided implementation to compute the LV volumes\n", "edv, esv = compute_left_ventricle_volumes(a2c_ed_lv_mask, a2c_es_lv_mask, a2c_voxelspacing, a4c_ed_lv_mask, a4c_es_lv_mask, a4c_voxelspacing)\n", "ef = round(100 * (edv - esv) / edv) # Round the computed value to the nearest integer\n", "\n", "print(f\"{patient_name=}: {ef=}, {edv=}, {esv=}\")" ] }, { "cell_type": "code", "execution_count": null, "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.10.0" } }, "nbformat": 4, "nbformat_minor": 4 }