6  PyNRRD

Code
from pyhere import here
import pandas as pd

import nrrd

6.1 seg.nrrd

6.1.2 Get Label value by Name

Code
import nrrd

def get_labelvalue_by_name(maskFilepath, name):
    """
    Retrieves the LabelValue of a segment given its name in a segmentation mask file.
    
    Parameters:
    - name (str): The name of the segment (e.g., "Segment_LE" or "Segment_RE").
    - maskFilepath (str): Path to the segmentation mask file (.seg.nrrd).
    
    Returns:
    - int: The LabelValue associated with the given segment name.
    - None: If the segment name is not found.
    """
    # Load the header of the NRRD file
    _, header = nrrd.read(maskFilepath)
    
    # Loop through the header to find the segment with the specified name
    segment_index = 0
    while True:
        # Construct the segment name key
        segment_name_key = f'Segment{segment_index}_Name'
        
        # Check if this segment key exists in the header
        if segment_name_key not in header:
            # If the key does not exist, we have exhausted all segments
            break
        
        # Check if this segment's name matches the specified name
        if header[segment_name_key] == name:
            # If it matches, retrieve the LabelValue for this segment
            label_value_key = f'Segment{segment_index}_LabelValue'
            return int(header[label_value_key])
        
        # Move to the next segment index
        segment_index += 1
    
    # Return None if the segment name was not found
    print(f"Segment with name '{name}' not found in the file '{maskFilepath}'.")
    return None
Code
get_labelvalue_by_name(here("data/MRI-Brain-Eye/Case1/Segmentation.seg.nrrd"), "Segment_LE")
1
Code
get_labelvalue_by_name(here("data/MRI-Brain-Eye/Case1/Segmentation.seg.nrrd"), "Segment_RE")
2