<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Makni Mariem on Medium]]></title>
        <description><![CDATA[Stories by Makni Mariem on Medium]]></description>
        <link>https://medium.com/@maknimariem11?source=rss-4c5804d3db06------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*EW0vYDkDT0Hb0y9AIALolg.png</url>
            <title>Stories by Makni Mariem on Medium</title>
            <link>https://medium.com/@maknimariem11?source=rss-4c5804d3db06------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 05:18:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@maknimariem11/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Your Guide to nnU-Net]]></title>
            <link>https://medium.com/@maknimariem11/your-guide-to-nnu-net-ee04103f8c22?source=rss-4c5804d3db06------2</link>
            <guid isPermaLink="false">https://medium.com/p/ee04103f8c22</guid>
            <category><![CDATA[medical-imaging]]></category>
            <category><![CDATA[brats]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[nnunet]]></category>
            <category><![CDATA[segmentation]]></category>
            <dc:creator><![CDATA[Makni Mariem]]></dc:creator>
            <pubDate>Sun, 04 Aug 2024 16:46:18 GMT</pubDate>
            <atom:updated>2024-08-14T16:57:44.780Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>nnU-Net automatically adjusts to different datasets, making choices about model setup and data processing that would normally require extensive manual effort. This tutorial is aimed at beginners who want to use nnU-Net without modifications, as well as researchers looking to evaluate or use this framework with their own datasets. Here, you’ll find straightforward steps to use both versions of nnU-Net, helping you to effectively apply this technology in your projects.</p><h3>Understanding nnU-Net</h3><p>nnU-Net (no-new-Net) stands as a self-configuring framework designed to streamline the development of deep learning models for volumetric (3D) and spatial (2D) medical image segmentation. Its architecture intelligently adapts to the characteristics of the dataset at hand, determining the most effective model configuration and pre-processing strategies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bFQrVT6a76rq19sx.png" /><figcaption>nnUNet architecture</figcaption></figure><p><strong>Versions Overview:</strong></p><ul><li><strong>nnU-Net v1:</strong> This initial version established the foundation for automated configuration and gained widespread adoption across various medical imaging challenges. However, it may present stability issues on Windows and generally lacks the user-friendliness found in subsequent versions.</li><li><strong>nnU-Net v2:</strong> Building on the groundwork of v1, version 2 further simplifies the user experience by enhancing automation in dataset handling and broadening support for multiple image file formats. This version is notably more user-friendly and provides greater customization options, making it adaptable to a wider range of applications.</li></ul><h3>nnU-Net v2</h3><h4>Setup</h4><p><strong>Step 1: Install nnU-Net v2</strong></p><p>Start by installing nnU-Net v2 using pip:</p><pre>pip install nnunetv2</pre><p><strong>Step 2: Create Directory Structure</strong></p><p>Organize your data by creating the following directories within your dataset folder:</p><ul><li>nnUNet_raw: Where raw data will be stored.</li><li>nnUNet_preprocessed: For storing preprocessed data.</li><li>nnUNet_results: Where training results will be saved.</li></ul><p>Within the nnUNet_raw directory, you should have:</p><ul><li>imagesTr: For training images.</li><li>labelsTr: For the corresponding labels.</li><li>imagesTs: For test images (optional).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GbufG-KVYk5_4tinOx9O2w.png" /><figcaption>Folders’ Structure</figcaption></figure><p><strong>Step 3: Set Environment Variables</strong></p><p>Define these environment variables in your terminal to tell nnU-Net where to find and save data:</p><pre>$Env:nnUNet_raw = &quot;path_to/nnUNet_raw&quot; <br>$Env:nnUNet_preprocessed = &quot;path_to/nnUNet_preprocessed&quot; <br>$Env:nnUNet_results = &quot;path_to/nnUNet_results&quot;</pre><p><strong>Step 4: Migrate from nnU-Net v1 (If applicable)</strong></p><p>If you’re upgrading from nnU-Net v1, convert your datasets to the v2 format with this command:</p><pre>nnUNetv2_convert_old_nnUNet_dataset INPUT_FOLDER OUTPUT_DATASET_NAME</pre><p>Remember that v2 uses DatasetXXX_Name format where XXX is the Dataset ID, unlike v1 which uses TaskXXX_Name. Thus this will look like:</p><pre>nnUNetv2_convert_old_nnUNet_dataset path_to/nnUNet_raw_data_base/nnUNet_raw_data/Task180_BratsMet Dataset180_BratsMet</pre><h3>Preparing New Datasets</h3><p><strong>For new datasets</strong>, you’ll need to arrange your training and testing data in the required format and create a dataset.json.</p><p>In my case, the training data was organized into separate folders for each patient, with each folder containing five files: four imaging modalities and one segmentation mask. Additionally, there was a folder for the test set, which contained similar imaging files but lacked segmentation masks</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B4mBDSaOFpiYbqIanQOdyg.png" /><figcaption>Data Conversion</figcaption></figure><p>Here’s a Python script to do so:</p><pre>import os<br>import shutil<br>from multiprocessing import Pool, get_context<br>import SimpleITK as sitk<br>from batchgenerators.utilities.file_and_folder_operations import *<br>from nnunetv2.dataset_conversion.generate_dataset_json import generate_dataset_json<br>from nnunetv2.paths import nnUNet_raw</pre><pre>def setup_nnunet_folders(base_dir, training_dir, test_dir, task_id, task_name):<br>    task_folder = f&quot;Dataset{task_id:03d}_{task_name}&quot;<br>    nnunet_base = os.path.join(nnUNet_raw, task_folder)<br>    imagesTr = os.path.join(nnunet_base, &#39;imagesTr&#39;)<br>    imagesTs = os.path.join(nnunet_base, &#39;imagesTs&#39;)<br>    labelsTr = os.path.join(nnunet_base, &#39;labelsTr&#39;)<br>    maybe_mkdir_p(imagesTr)<br>    maybe_mkdir_p(imagesTs)<br>    maybe_mkdir_p(labelsTr)</pre><pre>    case_ids = subdirs(training_dir, prefix=&#39;BraTS&#39;, join=False)<br>    for c in case_ids:<br>        shutil.copy(join(training_dir, c, c + &quot;-t1n.nii.gz&quot;), join(imagesTr, c + &#39;_0000.nii.gz&#39;))<br>        shutil.copy(join(training_dir, c, c + &quot;-t1c.nii.gz&quot;), join(imagesTr, c + &#39;_0001.nii.gz&#39;))<br>        shutil.copy(join(training_dir, c, c + &quot;-t2w.nii.gz&quot;), join(imagesTr, c + &#39;_0002.nii.gz&#39;))<br>        shutil.copy(join(training_dir, c, c + &quot;-t2f.nii.gz&quot;), join(imagesTr, c + &#39;_0003.nii.gz&#39;))<br>        shutil.copy(join(training_dir, c, c + &quot;-seg.nii.gz&quot;), join(labelsTr, c + &#39;.nii.gz&#39;))</pre><pre>    test_ids = subdirs(test_dir, prefix=&#39;BraTS&#39;, join=False)<br>    for c in test_ids:<br>        shutil.copy(join(test_dir, c, c + &quot;-t1n.nii.gz&quot;), join(imagesTs, c + &#39;_0000.nii.gz&#39;))<br>        shutil.copy(join(test_dir, c, c + &quot;-t1c.nii.gz&quot;), join(imagesTs, c + &#39;_0001.nii.gz&#39;))<br>        shutil.copy(join(test_dir, c, c + &quot;-t2w.nii.gz&quot;), join(imagesTs, c + &#39;_0002.nii.gz&#39;))<br>        shutil.copy(join(test_dir, c, c + &quot;-t2f.nii.gz&quot;), join(imagesTs, c + &#39;_0003.nii.gz&#39;))</pre><pre>    generate_dataset_json(nnunet_base, channel_names={0: &#39;T1&#39;, 1: &#39;T1ce&#39;, 2: &#39;T2&#39;, 3: &#39;Flair&#39;},<br>                          labels={&#39;background&#39;:0, &#39;necrotic and non-enhancing tumor core&#39;:1,<br>                                  &#39;edema&#39;:2, &#39;enhancing tumor&#39;:3},<br>                          num_training_cases=len(case_ids), file_ending=&#39;.nii.gz&#39;)<br></pre><pre>if __name__ == &#39;__main__&#39;:<br>    base_dir = &#39;path_to/nnUNet_raw/nnUNet_raw_data&#39;<br>    training_dir = &#39;path_to/training_data&#39;<br>    test_dir = &#39;path_to/testing_data&#39;<br>    task_id = 180<br>    task_name = &quot;BraTSMet&quot;</pre><pre>setup_nnunet_folders(base_dir, training_dir, test_dir, task_id, task_name)</pre><h3>Preprocessing and Training</h3><p><strong>Preprocessing :</strong></p><p>To start preprocessing, use:</p><pre>nnUNetv2_plan_and_preprocess -d DATASET_ID --verify_dataset_integrity</pre><p>nnU-Net will extract a dataset fingerprint (a set of dataset-specific properties such as image sizes, voxel spacings, intensity information etc). This information is used to design U-Net configurations and store them in dataset_fingerprint.jsonand nnUNetPlans.json .</p><p>Each U-Net configuration leads to a different pre-processing pipeline. The dataset is processed accordingly to match the requirements of each configuration, ensuring that the models are trained on data that is optimally prepared for the specific network architecture and settings.</p><p><strong>Training:</strong></p><p>To train the model on pre-processed data:</p><pre>nnUNetv2_train DATASET_NAME_OR_ID UNET_CONFIGURATION FOLD</pre><p><strong>UNET_CONFIGURATION</strong>: This specifies the network configuration to use. Options include:</p><ul><li>3d_fullres: Full resolution 3D U-Net.</li><li>3d_lowres: Lower resolution 3D U-Net, typically omitted in datasets with small image sizes to avoid redundancy.</li><li>2d: Two-dimensional U-Net.</li><li>3d_cascade_fullres: A cascading U-Net that uses outputs from 3d_lowres as inputs, enhancing details in full resolution.</li></ul><p><strong>FOLD</strong>: Indicates which fold (from 0 to 4) is to be used as the validation set. The remaining folds will be used for training.</p><p><strong>Full Cross-Validation:</strong> When using all the folds in training, known as full cross-validation, every part of the dataset is utilized for both training and validation at different times. This comprehensive approach ensures that the model is well-tested across diverse data subsets, enhancing its <strong>robustness and generalizability</strong></p><h4>Finding the Best Configuration:</h4><p>After training, to determine the most effective model setup, ensure all 5 folds have been processed for each configuration. Note that to use this feature, you must save the softmax outputs during training by including the --npz flag in the training:</p><pre>nnUNetv2_train DATASET_NAME_OR_ID UNET_CONFIGURATION FOLD --npz <br>nnUNetv2_find_best_configuration DATASET_NAME_OR_ID -c CONFIGURATIONS</pre><p><strong>CONFIGURATIONS</strong>: The list of the configurations you want to evaluate.</p><h4>Output Storage:</h4><p>The trained models will be saved to the nnUNet_results folder. Each training obtains an automatically generated output folder.</p><p>Example:</p><pre>nnUNet_results/<br>├── Dataset180_BratsMet<br> │── nnUNetTrainer__nnUNetPlans__3d_fullres<br> │ ├── fold_0<br> │ ├── fold_1<br> │ ├── fold_2<br> │ ├── fold_3<br> │ ├── fold_4<br> │ ├── dataset.json<br> │ ├── dataset_fingerprint.json<br> │ └── plans.json</pre><h3>nnU-Net v1:</h3><h4>Installation:</h4><pre>pip install nnunet</pre><h4>Environment Setup:</h4><p>Begin by creating the necessary directories. The structure is similar to nnU-Net v2 but includes some modifications:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gzJKiQ7WSHYzY6-LzjvqhQ.png" /><figcaption>Folders’ Structure</figcaption></figure><p>Configure the environment variables to link to these directories:</p><pre>$env:nnUNet_raw_data_base=&quot;path_to\nnUNet_raw_data_base&quot;<br>$env:nnUNet_preprocessed=&quot;path_to\nnUNet_preprocessed&quot;<br>$env:RESULTS_FOLDER=&quot;path_to\nnUNet_trained_models&quot;</pre><p>To accommodate nnUNet v1’s requirements, modify the existing scripts from v2. Use TaskXXX instead of DatasetXXX and adjust paths accordingly to match v1’s directory structure.</p><h4>Customizing dataset.json:</h4><p>In nnUNet v1, the structure of dataset.json requires a specific format where the list of training and testing samples should be included without the modality prefixes (like 0000, 0001, 0002, 0003). To configure this correctly, use the following Python script :</p><pre>from typing import Tuple<br>import os<br>import shutil<br>from glob import glob<br>import random<br>import numpy as np<br>import json<br><br>def get_identifiers_from_splitted_files(folder: str):<br>    # Collect all .nii.gz files in the folder<br>    file_paths = glob(os.path.join(folder, &#39;*.nii.gz&#39;))<br>    # Extract unique identifiers from the file paths<br>    uniques = np.unique([os.path.basename(f).split(&#39;_&#39;)[0] for f in file_paths])<br>    return uniques<br><br>def generate_dataset_json(output_file: str, imagesTr_dir: str, imagesTs_dir: str, modalities: Tuple,<br>                          labels: dict, dataset_name: str, sort_keys=True, license: str = &quot;hands off!&quot;, dataset_description: str = &quot;&quot;,<br>                          dataset_reference=&quot;&quot;, dataset_release=&#39;0.0&#39;):<br>    &quot;&quot;&quot;<br>    :param output_file: This needs to be the full path to the dataset.json you intend to write, so<br>    output_file=&#39;DATASET_PATH/dataset.json&#39; where the folder DATASET_PATH points to is the one with the<br>    imagesTr and labelsTr subfolders<br>    :param imagesTr_dir: path to the imagesTr folder of that dataset<br>    :param imagesTs_dir: path to the imagesTs folder of that dataset. Can be None<br>    :param modalities: tuple of strings with modality names. must be in the same order as the images (first entry<br>    corresponds to _0000.nii.gz, etc). Example: (&#39;T1&#39;, &#39;T2&#39;, &#39;FLAIR&#39;).<br>    :param labels: dict with int-&gt;str (key-&gt;value) mapping the label IDs to label names. Note that 0 is always<br>    supposed to be background! Example: {0: &#39;background&#39;, 1: &#39;edema&#39;, 2: &#39;enhancing tumor&#39;}<br>    :param dataset_name: The name of the dataset. Can be anything you want<br>    :param sort_keys: In order to sort or not, the keys in dataset.json<br>    :param license:<br>    :param dataset_description:<br>    :param dataset_reference: website of the dataset, if available<br>    :param dataset_release:<br>    :return:<br>    &quot;&quot;&quot;<br>    train_identifiers = get_identifiers_from_splitted_files(imagesTr_dir)<br><br>    if imagesTs_dir is not None:<br>        test_identifiers = get_identifiers_from_splitted_files(imagesTs_dir)<br>    else:<br>        test_identifiers = []<br><br>    json_dict = {}<br>    json_dict[&#39;name&#39;] = dataset_name<br>    json_dict[&#39;description&#39;] = dataset_description<br>    json_dict[&#39;tensorImageSize&#39;] = &quot;4D&quot;<br>    json_dict[&#39;reference&#39;] = dataset_reference<br>    json_dict[&#39;licence&#39;] = license<br>    json_dict[&#39;release&#39;] = dataset_release<br>    json_dict[&#39;modality&#39;] = {str(i): modalities[i] for i in range(len(modalities))}<br>    json_dict[&#39;labels&#39;] = {str(i): labels[i] for i in labels.keys()}<br><br>    json_dict[&#39;numTraining&#39;] = len(train_identifiers)<br>    json_dict[&#39;numTest&#39;] = len(test_identifiers)<br>    json_dict[&#39;training&#39;] = [<br>        {&#39;image&#39;: &quot;./imagesTr/%s.nii.gz&quot; % i, &quot;label&quot;: &quot;./labelsTr/%s.nii.gz&quot; % i} for i<br>        in<br>        train_identifiers]<br>    json_dict[&#39;test&#39;] = [&quot;./imagesTs/%s.nii.gz&quot; % i for i in test_identifiers]<br><br>    if not output_file.endswith(&quot;dataset.json&quot;):<br>        print(&quot;WARNING: output file name is not dataset.json! This may be intentional or not. You decide. &quot;<br>              &quot;Proceeding anyways...&quot;)<br>        <br>    # Save the JSON dictionary to a file<br>    with open(output_file, &#39;w&#39;) as f:<br>        json.dump(json_dict, f, indent=4, sort_keys=sort_keys)<br><br># Modalities in the order of their appearance in the filenames<br>modalities = (&#39;T1&#39;, &#39;T1ce&#39;, &#39;T2&#39;, &#39;Flair&#39;)<br><br># Labels as specified by the BRATS challeng<br>&quot;labels&quot;: {<br>        &quot;0&quot;: &quot;background&quot;,<br>        &quot;1&quot;: &quot;necrotic and non-enhancing tumor core&quot;,<br>        &quot;2&quot;: &quot;edema&quot;,<br>        &quot;3&quot;: &quot;enhancing tumor&quot;<br>    }<br># Dataset name, feel free to modify<br>dataset_name = &#39;Task180_BraTSMet&#39;<br><br># Now call the function to generate dataset.json<br>generate_dataset_json(<br>    output_file=os.path.join(&quot;Path_to/nnUNet_raw_data_base/nnUNet_raw_data/Task180_BraTSMet&quot;, &#39;dataset.json&#39;),<br>    imagesTr_dir=&quot;Path_to/nnUNet/nnUNet_raw_data_base/nnUNet_raw_data/Task180_BraTSMet/imagesTr&quot;,<br>    imagesTs_dir=&quot;Path_to/nnUNet/nnUNet_raw_data_base/nnUNet_raw_data/Task180_BraTSMet/imagesTs&quot;,<br>    modalities=modalities,<br>    labels=labels,<br>    dataset_name=dataset_name,<br>    license=&#39;hehe&#39;,  <br>    dataset_description=&#39;BRATS Met Brain Tumour Segmentation Dataset&#39;,<br>    dataset_reference=&#39;http:..&#39;,<br>    dataset_release=&#39;1.0&#39;<br>)</pre><p>The json file would be in this format:</p><pre>{<br>    &quot;description&quot;: &quot;BRATS Met Brain Tumour Segmentation Dataset&quot;,<br>    &quot;labels&quot;: {<br>        &quot;0&quot;: &quot;background&quot;,<br>        &quot;1&quot;: &quot;necrotic and non-enhancing tumor core&quot;,<br>        &quot;2&quot;: &quot;edema&quot;,<br>        &quot;3&quot;: &quot;enhancing tumor&quot;<br>    },<br>    &quot;licence&quot;: &quot;hehe&quot;,<br>    &quot;modality&quot;: {<br>        &quot;0&quot;: &quot;T1&quot;,<br>        &quot;1&quot;: &quot;T1ce&quot;,<br>        &quot;2&quot;: &quot;T2&quot;,<br>        &quot;3&quot;: &quot;Flair&quot;<br>    },<br>    &quot;name&quot;: &quot;Task180_BraTSMet&quot;,<br>    &quot;numTest&quot;: 1,<br>    &quot;numTraining&quot;: 5,<br>    &quot;reference&quot;: &quot;http:..&quot;,<br>    &quot;release&quot;: &quot;1.0&quot;,<br>    &quot;tensorImageSize&quot;: &quot;4D&quot;,<br>    &quot;test&quot;: [<br>        &quot;./imagesTs/BraTS-MET-00002-000.nii.gz&quot;<br>    ],<br>    &quot;training&quot;: [<br>        {<br>            &quot;image&quot;: &quot;./imagesTr/BraTS-MET-00002-000.nii.gz&quot;,<br>            &quot;label&quot;: &quot;./labelsTr/BraTS-MET-00002-000.nii.gz&quot;<br>        },<br>        {<br>            &quot;image&quot;: &quot;./imagesTr/BraTS-MET-00005-000.nii.gz&quot;,<br>            &quot;label&quot;: &quot;./labelsTr/BraTS-MET-00005-000.nii.gz&quot;<br>        }<br>    ]<br>}</pre><h4>Preprocessing and Training:</h4><p>Use the nnUNet_plan_and_preprocess command to preprocess the data and then train the model:</p><pre>nnUNet_plan_and_preprocess -d DATASET_ID --verify_dataset_integrity</pre><pre>nnUNet_train 3d_fullres nnUNetTrainerV2 TASK_ID FOLD</pre><p>As before, if you plan to use on Identifying the best U-Net configuration you’ll need to use — npz and train on all folds.</p><h3>Conclusion</h3><p>nnU-Net revolutionizes the process of medical image segmentation by automating much of the heavy lifting involved in model setup and optimization. It provides a robust and reliable framework that researchers and practitioners can utilize to enhance their work with minimal setup. This guide has walked you through the essential steps to use nnU-Net effectively.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ee04103f8c22" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[3D TransUNet: Advancing Medical Image Segmentation through Vision Transformer]]></title>
            <link>https://medium.com/@maknimariem11/3d-transunet-advancing-medical-image-segmentation-through-vision-transformer-35d7d204e53b?source=rss-4c5804d3db06------2</link>
            <guid isPermaLink="false">https://medium.com/p/35d7d204e53b</guid>
            <category><![CDATA[segmentation]]></category>
            <category><![CDATA[3d-segmentation]]></category>
            <category><![CDATA[medical-imaging]]></category>
            <category><![CDATA[unet]]></category>
            <dc:creator><![CDATA[Makni Mariem]]></dc:creator>
            <pubDate>Mon, 08 Jul 2024 10:14:04 GMT</pubDate>
            <atom:updated>2024-07-08T10:14:04.066Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>In this blog post, we delve into the realm of medical image segmentation with the <a href="https://arxiv.org/pdf/2310.07781"><strong>3D TransUNet</strong></a>, an advanced architecture that extends the capabilities of the previously successful <strong>TransUNet</strong> by incorporating three-dimensional data processing. The 3D TransUNet builds on the foundation of the <strong>nnU-Net framework </strong>renowned for its versatility in handling both 2D and 3D segmentation tasks. We will also present the different configurations of this model and assess their effectiveness and applications in various medical imaging contexts</p><h4><strong>The core strength of this architecture lies in two main components:</strong></h4><ul><li><strong>Transformer Encoder: </strong>This module leverages the transformer’s self-attention capabilities to enhance <strong>global context awareness</strong>, which is crucial for accurate <strong>multi-organ segmentation</strong>.</li><li><strong>Transformer Decoder: </strong>It focuses on <strong>refining segmentation accuracy</strong>, particularly useful for precisely <strong>identifying smaller and more challenging targets like tumors.</strong></li></ul><p>Our discussion will begin by examining the initial <strong>feature map</strong> from a CNN encoder <strong>(D*W*H*C)</strong> and how it transitions into a comprehensive <strong>label map</strong> <strong>(D*W*H)</strong>. For those new to this subject, I recommend checking out my previous blog on the standard <strong>TransUNet</strong>, where I cover the its architecture which sets the groundwork for understanding the more complex 3D TransUNet structure.</p><h3>Detailed Exploration of 3D TransUNet:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BJcprMqVJ5D6bObtVMQ3Yg.png" /><figcaption>3D TransUnet Architecture</figcaption></figure><h4>Transformer Encoder Workflow</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nnq4prOBwTFj7Uwt85goEg.png" /><figcaption>3D TransUnet Encoder</figcaption></figure><p>. <strong>Tokenization</strong>: The feature map is reshaped into a sequence of flattened 3D patches. Each patch is P×P×P, and the total number of patches N is calculated as N=(D×H×W)/ P³<br>. <strong>Patch Embedding and Positional Encoding</strong>: These vectorized patches are then mapped into a denc​-dimensional embedding space using a <strong>linear projection.</strong> <strong>Positional encodings</strong> are added to imbue spatial relationships within the data.<br>. <strong>Transformer Layers Execution</strong>: The feature representation is enhanced through multiple layers of self-attention and feed-forward networks. An example of layer operations includes:<br>- zl’= MSA(LN(zl-1))+zl-1<br>- zl=MLP(LN(zl’))+zl’</p><h4>Transformer Decoder Workflow:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*82es3vlzsmUCgjkN64B8mg.png" /><figcaption>3D TransUnet Decoder</figcaption></figure><h4><strong>Coarse Candidate Estimation</strong>:</h4><p><strong>Transition from Pixel-Wise to Query-Based Segmentation</strong>: Instead of classifying each pixel independently based on likelihood and using loss at pixel level, this approach utilizes <strong>organ queries </strong>where each query vector represents a specific organ or region. So in theory number of queries = number of classes but in reality we take it superiorto decrease False negatives.</p><p><strong>Initial Coarse Prediction (Z0​)</strong>: The first approximation of the segmentation map Z0​ is computed as Z0=g(P0×F′) where:</p><ul><li>g(⋅) is a sigmoid function followed by a thresholding operation set at 0.5.</li><li>P0​ represents the initial organ queries.</li><li>F′ denotes the transposed embedding of the final U-Net block feature, dimensioned as R^(D×H×W×dec) ​, d_dec​ is the dimensionality of the object queries.</li></ul><h4><strong>Transformer decoder:</strong></h4><p><strong>Refinement of Organ Queries</strong>: Each decoder layer refines the organ queries Pt​ by incorporating cross-attention with <strong>intermediate U-Net features</strong> using <strong>residual path</strong>. These features are mapped into the same dimensional space d_dec to facilitate the computation of cross-attention:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S2Hn93P430GHxt_L8jwoLA.png" /></figure><p>Where wq​, wk​, and wv are parametric weight matrices transforming P and F into queries, keys, and values, respectively.</p><h4><strong>coarse to fine attention refinement</strong>:</h4><p>This component utilizes a coarse mask derived from an initial estimation to guide the refinement process in subsequent iterations. By grounding the cross-attention within the regions identified in the coarse prediction, the model focuses more accurately on regions of interest, iteratively enhancing the segmentation accuracy.</p><p><strong>the iterative refinement process:<br></strong>During each iteration ttt, the organ queries are further refined based on the adjusted attention:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/690/1*Vc7XqR1rxK9qKTIIHrdjgw.png" /></figure><p>where:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/543/1*PmIWZDmQi9ABlnL4wTpQvw.png" /></figure><p>The updated organ queries PTP_TPT​ from the final iteration are decoded into a refined, binarized segmentation map ZTZ_TZT​ using the equation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/319/1*UqT1_zHezegYmEk0KirvXA.png" /></figure><p>This step associates each binarized mask with a specific semantic class, leveraging the final features for precise segmentation.</p><p>A linear layer with weight matrices wfc​ ∈ Rd×k projects the refined organ embeddings PT to the output class logits O, where k is the label index. The final class labels associated with the predicted masks ZT are determined by argmaxk(O) , identifying the most likely class for each segmented region.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/363/1*XHIlQmuhiQW6-2QEPIIlIA.png" /></figure><h3>Configuration Variants</h3><p><strong>1. Encoder Only Configuration:</strong></p><p>This configuration combines a CNN with a transformer encoder, followed by a traditional U-Net decoder. The loss is calculated using a combination of <strong>Dice loss</strong> and <strong>pixel-wise cross-entropy loss</strong>. These metrics focus on enhancing both the accuracy of segmentation boundaries and the pixel-level classification performance.</p><p><strong>2. Decoder Only Configuration:</strong></p><p>Utilizes a standard CNN encoder paired with a transformer-based decoder, emphasizing the refinement of segmentation outputs. The loss function includes <strong>Hungarian matching loss</strong>, which <strong>comprises pixel-wise class classification loss and binary mask loss</strong> for each segmented prediction. The formulation is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*UIb5NAb_jJxZNNXpeTGs_A.png" /></figure><p>Additionally, <strong>deep supervision</strong> is implemented by <strong>applying the training loss at the output at each stage of the decoder</strong>, ensuring that each layer contributes effectively to the learning process.</p><p><strong>3. Combined Encoder and Decoder:</strong></p><p>Integrates both the transformer encoder and decoder for a comprehensive and unified approach to segmentation. The combined configuration utilizes <strong>Hungarian matching loss</strong>, aiming to synergize the strengths of both the encoder and decoder in a single coherent framework.</p><h3>Effectiveness and Applications</h3><p><strong>Encoder Only:</strong> This setup shows superior performance in <strong>multi-organ segmentation tasks</strong>. The combination of CNN and transformer encoder efficiently captures both local and global features necessary for distinguishing between different organs in a complex anatomical landscape.</p><p><strong>Decoder Only:</strong> More effective for <strong>tumor segmentation</strong>, where precision in identifying small, often irregularly shaped targets is critical. The transformer-based decoder excels in refining segmentation outputs, making it ideal for detailed and nuanced tasks like tumor detection.</p><p><strong>Combined Encoder and Decoder:</strong> While <strong>theoretically promising</strong>, the combined approach <strong>does not offer further enhancements for either multi-organ or hepatic vessel segmentation compared to using the configurations separately</strong>. This could be due to an overlap in the functionalities or counteractive effects between the encoder and decoder components.</p><p><strong>Query Number:</strong> Increasing the number of queries beyond the number of classes generally improves the model’s ability to reduce false negatives. <strong>However, further augmentation of queries</strong> shows no benefit, indicating an optimal threshold for the number of queries based on the specific application needs.</p><h3>Conclusion</h3><p>The 3D TransUNet presents a flexible architecture with multiple configurations, each suited to specific types of medical image segmentation tasks. While each configuration has its strengths, the optimal choice depends on the specific requirements of the segmentation task at hand.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=35d7d204e53b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Demystifying Medical Imaging: Modalities, Data Formats, and Segmentation]]></title>
            <link>https://medium.com/@maknimariem11/demystifying-medical-imaging-modalities-data-formats-and-segmentation-411619553342?source=rss-4c5804d3db06------2</link>
            <guid isPermaLink="false">https://medium.com/p/411619553342</guid>
            <category><![CDATA[medical-imaging]]></category>
            <category><![CDATA[segmentation]]></category>
            <category><![CDATA[mri]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[nifti]]></category>
            <dc:creator><![CDATA[Makni Mariem]]></dc:creator>
            <pubDate>Tue, 02 Jul 2024 09:26:48 GMT</pubDate>
            <atom:updated>2024-07-02T09:26:48.978Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Imagine a world where doctors can peek inside the human body without making a single incision. This is the reality of medical imaging, or radiology, a pivotal field of medicine that encompasses a range of non-invasive tests, enabling physicians to diagnose injuries and diseases with precision while minimizing patient discomfort.</p><p>Segmentation, the process of isolating specific areas within an image, has emerged as a focal point in medical imaging, driving innovation in over <strong>70% of biomedical image analysis competitions</strong>. In this blog, we will explore the multifaceted purpose of medical imaging, delve into the most commonly used imaging modalities and data formats, and explain the nuances of 2D versus 3D image processing. We’ll tackle the inherent challenges in the field, from data variability to technological limitations. Further, we will break down the concept of segmentation, introduce key evaluation metrics used to measure its efficacy, and focus particularly on brain segmentation, highlighting the modalities that offer the most insight. Join us as we navigate the complex yet fascinating world of medical imaging</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/962/1*U_x9M3cyJCrIke0lPScMtQ.png" /><figcaption><a href="https://www.nature.com/articles/s41467-018-07619-7">Overview of biomedical image analysis challenges</a></figcaption></figure><h3>Purpose of Medical Imaging</h3><p>Medical imaging uses a range of technologies such as ultrasound, magnetic resonance imaging (MRI), nuclear medicine, and X-rays. Each of these modalities plays a crucial role in modern healthcare:</p><ul><li><strong>Diagnosis</strong>: By providing clear images of internal organs and structures, medical imaging is instrumental in diagnosing a wide array of conditions, from fractures and tumors to infections and vascular diseases.</li><li><strong>Surgical Planning and Guidance</strong>: Imaging technologies are essential in planning surgical procedures, allowing surgeons to navigate complex operations with higher precision. For instance, MRI and CT scans can be used to map out a surgical path before making an incision.</li><li><strong>Treatment Monitoring</strong>: Medical imaging is vital in tracking the progress of treatments, such as the shrinkage of tumors during chemotherapy or the healing of bones after surgery.</li><li><strong>Research</strong>: Beyond clinical applications, medical imaging contributes to medical research by offering insights into disease progression, treatment responses, and more, facilitating the development of new therapies and interventions.</li></ul><h3>Common Imaging Modalities</h3><ul><li><strong>X-Ray:</strong> X-rays are a type of <strong>electromagnetic radiation</strong> that can pass through the body, capturing images primarily of the bones and other dense structures. This modality is frequently used for detecting bone fractures, dental issues, and chest imaging, such as looking for lung abnormalities.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Faer0FtkBNRsl41I" /><figcaption><a href="https://www.ucsfhealth.org/medical-tests/x-ray---skeleton">Xray Skeleton scans</a></figcaption></figure><ul><li><strong>CT Scans:</strong> CT (Computed Tomography) scans use X-rays to create detailed cross-sectional images of the body. They<strong> measure the X-ray absorption of different tissues</strong>, which is outputted as a <strong>grayscale image where each pixel represents a specific density.</strong> The scale in CT scans is <strong>absolute</strong>, meaning the intensities relate to real physical properties and can be compared across different scans. CT scans are invaluable in diagnosing internal injuries, tumors, and complex bone fractures.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*seVdii_6OVEn0Hob.jpg" /><figcaption><a href="https://www.lompocvmc.com/blogs/2021/december/12-reasons-you-may-need-a-ct-scan/">CT Scan</a></figcaption></figure><ul><li><strong>MRI (Magnetic Resonance Imaging):</strong> Unlike CT scans and X-rays, MRI uses <strong>magnetic fields and radio waves </strong>to produce images. This modality is highly effective for imaging soft tissues such as the brain, muscles, and connective tissues. The intensity scale in MRI is relative, varying with different signal properties, which means <strong>images can differ across scanners and even within the same scan under different settings.</strong></li><li><strong>Ultrasound:</strong> Ultrasound imaging utilizes <strong>high-frequency sound waves</strong> to create images of the inside of the body. It is commonly used during pregnancy to monitor the developing foetus, but also serves well for examining organs like the heart, liver, and kidneys. Ultrasound is safe, non-invasive, and does not use ionizing radiation.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/259/0*0UYvhuBAD8qkuOlA" /><figcaption><a href="https://raisingchildren.net.au/pregnancy/health-wellbeing/tests-appointments/12-week-ultrasound-pregnancy-scan">ultrasound scan</a></figcaption></figure><ul><li><strong>PET Scans:</strong> PET (Positron Emission Tomography) scans are a type of <strong>nuclear medicine imaging</strong> that involves injecting a small amount of <strong>radioactive material</strong> into the body to help visualize function rather than structure. PET scans are particularly useful for detecting cancer, monitoring cancer treatment, and evaluating brain abnormalities such as tumors, memory disorders, and seizures.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*Mdf635wEogRZxy7m.jpg" /><figcaption><a href="https://alzheimersnewstoday.com/news/fdg-pet-scan-accurately-assesses-cognitive-decline-severity-alzheimers-disease/">PET scan</a></figcaption></figure><h3>Data Format</h3><p>Several data formats such as Analyze, MINC, Interfile, ECAT, RAW, and MHA/MHD are used in medical imaging, each tailored to specific modalities and research needs. However, in this blog, we will focus primarily on the <strong>most commonly used</strong> formats — NIfTI and DICOM — due to their widespread adoption and critical role in everyday medical imaging processes:</p><ul><li><strong>NIfTI Files:</strong> NIfTI (Neuroimaging Informatics Technology Initiative) files, typically with extensions .nii or compressed as .nii.gz, are widely used in medical imaging. These files represent <strong>3D volumes</strong> and can encompass an entire <strong>series of DICOM images</strong> in one file, making them highly efficient for storage and handling in medical research and analysis.</li><li><strong>DICOM (Digital Imaging and Communications in Medicine):</strong> DICOM is the <strong>standard format for storing and transmitting</strong> medical imaging information. Each DICOM file contains<strong> one slice of a 3D dataset</strong>, which can appear <strong>almost 2D due to the very small depth of each slice</strong>, but in reality, these slices comprise a 3D volume when assembled. These files are detailed, including patient information, imaging parameters, and the imaging data itself, <strong>composed of voxels.</strong></li><li><strong>Voxels:</strong> Voxels are the <strong>three-dimensional equivalent of pixels</strong>, representing a value on a regular grid in a three-dimensional space. <strong>Typically, the X and Y dimensions are larger than the Z dimension (depth)</strong>, which allows detailed cross-sectional images while maintaining manageable file sizes.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/556/0*hPsb0MDEw7c0XhMM.jpg" /><figcaption><a href="https://carpentries-incubator.github.io/SDC-BIDS-IntroMRI/anatomy-of-nifti.html">Voxels Visualization</a></figcaption></figure><p><strong>Voxel Spacing:</strong> Voxel spacing refers to <strong>the distance between the centers of adjacent voxels</strong>. This spacing <strong>can vary significantly due to differences in scanners and scanning protocols.</strong> Variations in voxel spacing can <strong>affect the uniformity of the data</strong>, which necessitates <strong>resampling</strong> to ensure consistency across datasets for comparative and analytical purposes. Resampling adjusts voxel dimensions to a common scale, which is crucial for accurate volume measurements, 3D reconstructions, and application in computational models.</p><h3><strong>2D vs. 3D Imaging Approaches</strong></h3><h4><strong>2D Imaging:</strong></h4><p>2D models are trained on individual slices, creating masks for each slice. These 2D masks are then stacked along the z-axis to form a 3D segmentation. However, this method can <strong>miss important depth information</strong>, leading to less accurate results. This limitation can be critical in cases like tumor segmentation, where the presence of a tumor in one slice increases the likelihood of its presence in adjacent slices.</p><p>Advanced models use techniques like recurrent neural networks (RNNs) or pseudo-3D convolutions on stacked slices to address these limitations. Plus accurate 3D reconstructions depend on proper alignment and interpolation of these slices.</p><h4><strong>3D Imaging:</strong></h4><p>3D imaging captures comprehensive views including depth but has its own challenges:</p><ul><li><strong>Performance Issues:</strong> <strong>Anisotropic datasets, where voxel dimensions vary between the axes,</strong> need additional processing to normalize, which is computationally intensive.</li><li><strong>Computational Constraints:</strong> Handling the large data volume in 3D scans often requires working with patches or subvolumes. This can be problematic for large organs, as each patch may lack sufficient context for accurate analysis. Brain scans are less affected since patches can still provide significant contextual data.</li></ul><h3>Challenges in Medical Imaging</h3><ul><li><strong>Variability in Data</strong>: arises from several sources including <strong>different imaging technologies</strong>, <strong>operator differences</strong>, and <strong>patient-specific factors</strong> such as age, size, or medical condition. This variability can affect everything from <strong>image quality</strong> to the <strong>interpretation of results.</strong></li><li><strong>Anisotropic Data</strong>: Anisotropic data refers to the situation where <strong>voxel spacing varies among different dimensions</strong>. For example, in some imaging modalities like MRI, <strong>the resolution might be high in the plane (x and y axes) but much lower along the z-axis (depth)</strong>. To address this, <strong>resampling techniques</strong> are used to achieve <strong>isotropic voxel spacing</strong>, where data is interpolated to ensure <strong>uniform spacing</strong> across all dimensions.</li></ul><h3>Segmentation</h3><p>Segmentation in medical imaging is a critical process where specific regions or structures within an image are identified and separated from the rest of the image. This process can be broadly divided into two types:</p><ul><li><strong>Semantic Segmentation:</strong> This technique classifies each pixel in an image based on its semantic meaning, effectively<strong> treating all objects within the same category as a single entity</strong>. In medical imaging, semantic segmentation is used to <strong>delineate structures such as organs or tissues</strong>. For example, in a brain MRI, semantic segmentation might be used to <strong>differentiate various brain regions or to identify all areas affected by a certain pathology</strong>, regardless of their specific instance</li><li><strong>Instance Segmentation:</strong> Unlike semantic segmentation, instance segmentation not only identifies the category of each pixel but also <strong>distinguishes between different instances of the same category</strong> within the image.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/0*5s9hsrGI4bdww-We.png" /><figcaption><a href="https://www.folio3.ai/blog/semantic-segmentation-vs-instance-segmentation/">Semantic vs Instance Segmentation</a></figcaption></figure><h4>Segmentation Techniques</h4><ul><li><strong>Manual Segmentation:</strong> This traditional method involves a human expert who meticulously outlines the areas of interest within an image. While manual segmentation is <strong>highly accurate</strong>, it is extremely <strong>time-consuming and labor-intensive</strong>.</li><li><strong>Automated Segmentation:</strong> In contrast, automated segmentation uses algorithms to quickly and consistently delineate structures within an image. While <strong>faster and less subject to human error in repetitive tasks</strong>, automated methods require careful setup and validation to ensure accuracy.</li></ul><h4><strong>Latest Advances in Segmentation:</strong></h4><p>The field of automated segmentation has seen significant advancements with the integration of sophisticated neural network architectures. The <strong>nnU-Net framework</strong>, for instance, adapts itself to any given dataset, optimizing its configuration to enhance segmentation performance. Moreover, the incorporation of <strong>Transformer</strong> technology in U-Net architectures, exemplified by TransUNet, leverages attention mechanisms that significantly improve the model’s ability to focus on relevant features for more accurate segmentation. Additionally, <strong>the Medical Open Network for AI (MONAI) framework</strong> provides tools and pre-trained models that facilitate the development and deployment of AI-based medical imaging applications…</p><h3>Evaluation Metrics</h3><p>In the field of medical imaging, particularly in segmentation, it’s crucial to have robust metrics to evaluate the accuracy and efficacy of different techniques. The following are<strong> some of the standard metrics used</strong>:</p><p><strong>Dice Coefficient (Sørensen-Dice Index):</strong> This metric <strong>measures the similarity between two sets of data</strong>. In the context of segmentation, it calculates the <strong>overlap between the predicted segmentation and the ground truth</strong>, providing a score between 0 (no overlap) and 1 (perfect overlap).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/0*Lk7JSxapwI4qOHYM.png" /></figure><p><strong>Intersection over Union (IoU):</strong> Also known as the <strong>Jaccard Index</strong>, this metric is used to quantify the <strong>percent overlap</strong> between the target mask and the prediction output. Similar to the Dice coefficient, IoU is a measure from 0 to 1. <a href="https://medium.datadriveninvestor.com/deep-learning-in-medical-imaging-3c1008431aaf">https://medium.datadriveninvestor.com/deep-learning-in-medical-imaging-3c1008431aaf</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/796/0*Y5yQzziG7pa4MB17.png" /></figure><p><strong>Hausdorff Distance:</strong> This metric measures the extent to which each point of a predicted segmentation lies near some point of the ground truth segmentation, providing a measure of the<strong> largest error between the predicted and true boundaries</strong>. It is particularly useful in contexts where the most extreme values are significant, such as in ensuring that no part of a tumor is missed in segmentation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CnzFeSi6DMAMu-nRAhOU5A.png" /></figure><p><strong>Area Under the ROC Curve (AUC-ROC)</strong>: The ROC curve plots the true positive rate (sensitivity) against the false positive rate (1 — specificity) at different threshold levels. The AUC represents <strong>the degree or measure of separability achieved by the model.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NfAz0SR4s9QFMLXP.png" /><figcaption><a href="https://www.statology.org/compare-roc-curves/">AUC ROC</a></figcaption></figure><h3>Basics of Brain Tumors and Their Imaging</h3><h4><strong>Types of Brain Tumors</strong>:</h4><p>Brain tumors can be broadly categorized into two main types:</p><ol><li><strong>Gliomas:</strong> These are tumors that arise from glial cells, which support and protect neurons.</li><li><strong>Metastases:</strong> These tumors originate from cancer cells that have spread to the brain from other parts of the body. Metastatic brain tumors are typically multiple and can appear anywhere in the brain.</li></ol><h4><strong>Role of Imaging in Diagnosis and Treatment Planning</strong>:</h4><p>Imaging plays a crucial role in the diagnosis, characterization, and treatment planning of brain tumors. Different imaging modalities and MRI sequences are used to gather detailed information about the tumor’s size, location, type, and impact on surrounding brain structures.</p><h4><strong>Common modalities used :</strong></h4><p>MRI is the primary imaging modality used for brain tumors. Several <strong>MRI sequences</strong> provide complementary information:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MtUBJOnC6GnWXXsKwRvn-w.jpeg" /><figcaption><a href="https://www.frontiersin.org/journals/computational-neuroscience/articles/10.3389/fncom.2019.00084/full">MRI Sequences</a></figcaption></figure><ul><li><strong>T1-Weighted MRI:</strong> Provides high-resolution images of the brain’s anatomy. Tumors often appear as hypointense (dark) areas relative to the surrounding brain tissue.</li><li><strong>T1 Post-Contrast (Gadolinium-Enhanced) MRI:</strong> Enhances the visibility of the tumor. The contrast agent highlights areas of increased blood-brain barrier permeability, which is common in tumors, making them appear bright on the images.</li><li><strong>T2-Weighted MRI:</strong> Offers detailed images of brain tissue and fluid. Tumors typically appear hyperintense (bright) on T2-weighted images. This sequence is useful for assessing tumor edema and the extent of infiltration into surrounding brain tissue.</li><li><strong>FLAIR (Fluid-Attenuated Inversion Recovery) MRI:</strong> Suppresses the signal from cerebrospinal fluid, providing clear images of lesions near the fluid spaces. FLAIR is particularly useful for detecting peritumoral edema and small lesions that might be missed on other sequences.</li></ul><h3>Conclusion</h3><p>This blog covered the purposes of medical imaging, common modalities, data formats, and the differences between 2D and 3D approaches. We also explored segmentation techniques, evaluation metrics, and the specific use of MRI sequences in brain tumor imaging. Advancements in imaging technology and AI are continuously enhancing diagnostic accuracy and treatment planning. As these technologies evolve, they will further improve patient care and outcomes, making medical imaging an indispensable part of modern medicine.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=411619553342" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TransUNet: Transformers Make Strong Encoders for Medical Image Segmentation]]></title>
            <link>https://medium.com/@maknimariem11/transunet-transformers-make-strong-encoders-for-medical-image-segmentation-2646419be4bb?source=rss-4c5804d3db06------2</link>
            <guid isPermaLink="false">https://medium.com/p/2646419be4bb</guid>
            <dc:creator><![CDATA[Makni Mariem]]></dc:creator>
            <pubDate>Sun, 30 Jun 2024 16:04:34 GMT</pubDate>
            <atom:updated>2024-06-30T16:04:34.112Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>In this blog post, we’ll explore <a href="https://arxiv.org/pdf/2102.04306"><strong>TransUNet</strong></a>, an innovative architecture that enhances the well-known <strong>U-Net</strong> model by integrating a transformer encoder, specifically the Vision Transformer (<strong>ViT</strong>). We will start by understanding the basic structure of U-Net and the improvements made through these adjustments. By breaking down the architecture and explaining key concepts, I aim to provide a clear and comprehensive understanding of how TransUNet works and why it represents a significant advancement in medical image segmentation.</p><h3>U-Net</h3><p>In this diagram, we see the <strong>U-Net architecture</strong>, which is designed for <strong>biomedical image segmentation</strong>. This model is known for its distinctive “U” shape, resulting from an <strong>encoder-decoder setup</strong> with <strong>skip connections</strong> that help preserve important details.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*yDr8MfOxUSqgaKBd.png" /><figcaption><a href="https://datasciencetoday.net/index.php/en-us/deep-learning/228-unet">2D UNet Architecture</a></figcaption></figure><h4><strong>Encoder:</strong></h4><p>The left side of the U-Net is the encoder, which utilizes a convolutional Neural Network (CNN) similar to those used in image classification. It works by progressively reducing the <strong>spatial dimensions</strong> of the input image (making it smaller in size) while increasing the <strong>depth</strong> (number of channels). This process outputs a <strong>feature map</strong> that captures the information extracted from the image. Each step down in the encoder involves:</p><ul><li>A <strong>convolution operation </strong>(purple arrows), which extracts features from the image.</li><li>A<strong> ReLU</strong> activation, which helps the model to learn non-linear features.</li><li>A <strong>max-pooling</strong> operation (red arrows), which reduces the dimensionality of the feature maps by selecting the most prominent features of the previous one.</li></ul><h4><strong>Decoder:</strong></h4><p>The right side is the decoder, which performs the opposite function of the encoder. It progressively restores the spatial dimensions to match the size of the original image, aiming to pinpoint the exact location of objects. Each step up in the decoder includes:</p><ul><li>An <strong>up-convolution operation</strong> (green arrows), which enlarges the feature maps.</li><li>A <strong>concatenation </strong>with the corresponding encoder feature map (gray arrows). This step is crucial and is facilitated by the <strong>skip connections</strong> that directly bring features from the encoder to the decoder. These connections help the model <strong>remember precise details about the image structure, which might be lost during the encoding process.</strong></li></ul><p>At the end, a <strong>convolution</strong> converts the feature map into the final <strong>segmentation map</strong>, which classifies each pixel of the input image into different categories based on the model’s training.</p><h4><strong>Limitations:</strong></h4><p>While U-Net is powerful for many tasks, it has limitations. It struggles with modeling <strong>long-range dependencies</strong> since it focuses predominantly on local details and may lose global information. Additionally, its performance can be weak for target structures with large <strong>inter-patient variations</strong>, such as in medical images where tumors may differ significantly in texture, shape, and size across different patients.</p><h3>Transformers</h3><p>Originally designed for natural language processing (NLP), transformers have been adapted for image processing as <a href="https://arxiv.org/pdf/2010.11929"><strong>Vision Transformers (ViT)</strong></a>. ViT adapts the transformer architecture for visual data by treating images as sequences of pixels or small image patches.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/685/0*varJy2SlIPWj7uze.png" /><figcaption><a href="https://www.nature.com/articles/s41598-023-48004-9">ViT Architecture</a></figcaption></figure><h4><strong>Key Components of ViT:</strong></h4><p><strong>1- Self-Attention Mechanisms:</strong></p><ul><li>The core strength of ViT is its self-attention mechanism, which dynamically weighs the importance of various parts of an image. This enables ViT to capture the “global context,” highlighting key features necessary for specific tasks.</li></ul><p><strong>2- MSA (Multihead Self-Attention):</strong></p><ul><li>ViT uses <strong>MSA</strong> to focus on multiple image parts simultaneously. By dividing the input into several “heads,” it processes different aspects in parallel, thus capturing a broader range of information like feature types and spatial relationships.</li></ul><p><strong>3- MLP (Multilayer Perceptron):</strong></p><ul><li>Post self-attention, ViT processes features through an MLP, which consists of fully connected layers capable of learning non-linear feature combinations. The MLP integrates information across attention heads, enhancing the model’s ability to discern complex patterns and relationships.</li></ul><p><strong>4- Transferability:</strong></p><ul><li>A major advantage of ViT is its transferability, allowing a model trained on a large dataset to be effectively adapted to new, related tasks with minimal adjustment, thanks to its rich, generalized feature representations.</li></ul><h4><strong>Limitations and Integration with CNNs:</strong></h4><p>Despite its strengths, ViT struggles with <strong>localization</strong>, often failing to pinpoint exact object locations within an image due to its 1D sequence processing approach. This leads to<strong> lower resolution outputs</strong> when used solely with CNN decoders.</p><p><strong>The TransUNet architecture</strong> addresses this by <strong>combining ViT’s global focus with the local precision of CNNs.</strong></p><h3>TransUnet</h3><p>TransUNet is a hybrid architecture that combines CNN and Transformer technologies to leverage both high-resolution spatial information from CNNs and global contextual insights from Vision Transformers (ViTs). This integration allows for precise image segmentation, particularly useful in medical imaging.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Xxb47-eg5JPa_b34.png" /><figcaption>TransUNet Architecture</figcaption></figure><h4><strong>Architecture Components:</strong></h4><ul><li><strong>Encoder:</strong> The encoder features a dual approach, starting with a CNN encoder that processes the input image into a feature map. This feature map is then <strong>tokenized into patches</strong>, which are processed by a Transformer encoder. This setup captures both local details and global patterns effectively.</li><li><strong>Decoder:</strong> The decoder uses the features encoded by the Transformer and <strong>upsamples</strong> them, integrating them back with the high-resolution feature maps from the CNN. This step is crucial for precise localization of the segmentation areas.</li></ul><h4><strong>Detailed Encoder Process:</strong></h4><ol><li><strong>Initial CNN Processing: </strong>The input image is first processed by a CNN, which generates a <strong>feature map </strong>of dimensions H×W. This feature map captures localized features from the image, providing a rich basis for further processing.</li></ol><p><strong>2. Tokenization:</strong></p><p>Thefeature map is divided into patches of size P×P. Each patch is then flattened into a 1D sequence, resulting in an array of N tokens, where</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/95/1*R4eFFj9f9QgnNOkg98O-RA.gif" /></figure><p>The tokens represent parts of the original image but in a format suitable for transformer processing. Each token from the patches is denoted as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/164/1*-alG9IiT9t5LzZPzrXtxxA.png" /></figure><p>indicating its position in the sequence.</p><p><strong>3. Patch Embedding:</strong></p><p>Each token x_{i,p} is transformed into a D-dimensional embedding space using a<strong> trainable linear projection</strong>, commonly referred to as the embedding matrix</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/96/1*LtQEoohyo8AGQzl7rXi9Eg.gif" /></figure><p>essentially reshaping and projecting the input tokens into a higher-dimensional space. Positional embeddings Epos are added to these embeddings to incorporate the spatial relationships between different patches, forming the initial sequence for the transformer:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/92/1*wkfeXNa-W-zdmqBt1PT3Hw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/248/1*SVLxEx09j2RhlasyyIoXXg.png" /></figure><p>This sequence z0​ now represents the image in a form that preserves both content and positional context, facilitating the global contextual processing by the transformer.</p><p><strong>4. Transformer Processing:</strong></p><p>The sequence of embedded patches z0 is fed into the transformer’s layers, each comprising Multihead Self-Attention (MSA) and Multilayer Perceptron (MLP) blocks:</p><ul><li><strong>MSA Layer:</strong> At each layer L , the sequence undergoes self-attention where the model computes attention scores between all patches, allowing it to focus on different parts of the image based on their relevance to the segmentation task. The output of the MSA layer for each token is a combination of its own features and features from other tokens, weighted by their calculated attention scores:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/224/1*vJu1P6yNWVHTCw7fFb67cQ.png" /></figure><ul><li><strong>MLP Layer:</strong> Following the self-attention, each token’s features are passed through an MLP, which can further refine features by applying nonlinear transformations:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/201/1*2wDAMntlxmIUeIfqW1sIaQ.png" /></figure><h4><strong>Detailed Decoder Process:</strong></h4><p>The paper discusses the possibility of using a ‘naive’ approach with the decoder by leveraging Bilinear Upsampling and shows that this <strong>leads to loss of low level details</strong>. Thus cascade upsampler (CUP) is used in TransUNet.</p><p><strong>Cascade Upsampler (CUP):</strong></p><p>con sists of multiple upsampling steps to decode the hidden feature for outputting the nal segmentation mask. After reshaping the sequence of hidden feature we instantiate CUP by cascading multiple upsampling blocks for reaching the full resolution from H*P/ W*P to H*W. where each block consists of:</p><ul><li>Two upsampling operators.</li><li>A 3×33 \times 33×3 convolutional layer.</li><li>ReLU activation function.</li></ul><h3><strong>Parameters Used</strong></h3><p>The study strategically selects specific parameter settings to optimize the TransUNet’s performance:</p><ul><li><strong>Default Image Size:</strong> 224x224 pixels</li><li><strong>Patch Size:</strong> 16</li><li><strong>Batch Size:</strong> 24</li></ul><p><strong>Why these choices?</strong></p><p>These parameters are chosen based on their ability to balance detailed image processing with computational efficiency. However, you might wonder about <strong>the implications of altering these parameters</strong>.</p><h4><strong>Impact of Configuration Variations:</strong></h4><p><strong>1- Skip Connections:</strong></p><p>Increasing the number of skip connections improves model performance. This enhancement occurs because more connections allow better integration of local details and global context.</p><p>Optimal results are achieved by inserting skip connections at all three intermediate upsampling stages of the Cascade Upsampler (CUP), excluding the output layer.</p><p>This can be improved by using <a href="https://www.sciencedirect.com/science/article/pii/S1361841518306133"><strong>additive transformers</strong></a><strong> </strong>but due to their computational cost they weren’t adopted in TransUNet architecture.</p><p><strong>2- Input Resolution:</strong></p><p>Using higher resolutions betters the details available for segmentation, which can lead to more accurate outcomes. However, this advantage comes with <strong>increased computational demands </strong>and <strong>greater resource consumption</strong>, necessitating a careful balance.</p><p><strong>3- Patch Size:</strong></p><p>Reducing patch size <strong>increases the number of patches</strong> and, consequently, the <strong>number of connections</strong> within the model, which enhances its capability to capture complex details. This leads to improved segmentation accuracy.</p><p><strong>4- Model Scaling:</strong></p><p>Enlarging the model — by adding more layers or increasing parameters — generally results in better performance. However Larger configurations demand significantly more computational resources, making them less feasible for certain applications.</p><p>TransUNet is available in both Base and Large configurations to cater to different computational capabilities.</p><h3>Conclusion</h3><p>The TransUNet architecture predominantly processes images in 2D, managing each image slice independently before synthesizing the segmented outputs. This 2D approach, while efficient, may lead to information loss — especially noticeable in applications like tumor segmentation, where continuity between slices can indicate the presence of tumors.</p><p>To address this limitation, a 3D handling approach has been considered, which processes data in sub-volumes or patches. This method not only preserves spatial continuity but also manages computational costs effectively. The development and details of the <a href="https://arxiv.org/pdf/2310.07781">3D TransUNet </a>architecture will be explored in future blog posts.</p><p>For a deeper understanding and further insights, including comparisons with R50 Unet, AttnUnet, and ViT-CUP, the full <a href="https://arxiv.org/pdf/2102.04306">article</a> is available for those interested. It provides extensive results and discussions that enhance our understanding of TransUNet’s capabilities. I highly encourage all readers to delve into the article for a comprehensive exploration of these innovative segmentation solutions.</p><p>References:</p><p><a href="https://arxiv.org/pdf/1505.04597">U-Net: Convolutional Networks for Biomedical Image Segmentation</a></p><p><a href="https://datasciencetoday.net/index.php/en-us/deep-learning/228-unet">Architecture U-Net</a></p><p><a href="https://www.nature.com/articles/s41598-023-48004-9">Comparison between vision transformers and convolutional neural networks to predict non-small lung cancer recurrence</a></p><p><a href="https://arxiv.org/pdf/2102.04306">TransUNet: Transformers Make Strong Encoders for Medical Image Segmentation</a></p><p><a href="https://www.sciencedirect.com/science/article/pii/S1361841518306133">Attention gated networks: Learning to leverage salient regions in medical images</a></p><p><a href="https://arxiv.org/pdf/2010.11929">An Image is worth 16*16 words: Transformers for Image Recognition at Scale</a></p><p><a href="https://arxiv.org/pdf/2310.07781">3D TransUNet: Advancing Medical Image Segmentation through Vision Transformers</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2646419be4bb" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>