Code
from pyhere import here
import pandas as pd
import nrrdfrom pyhere import here
import pandas as pd
import nrrdseg.nrrdseg.nrrd file Infoimport nrrd
def print_seg_nrrd_info(path):
"""Print segment information from NRRD file.
"""
# Load the NRRD file
data, header = nrrd.read(path)
# Initialize a dictionary to store segment information
segments_info = {}
# Loop through metadata to extract segment information
for i in range(2): # Assuming 2 segments
segment_id = header.get(f'Segment{i}_ID', 'N/A')
label_value = header.get(f'Segment{i}_LabelValue', 'N/A')
layer = header.get(f'Segment{i}_Layer', 'N/A')
name = header.get(f'Segment{i}_Name', 'N/A')
# Store information in dictionary
segments_info[f'Segment_{i}'] = {
'ID': segment_id,
'LabelValue': label_value,
'Layer': layer,
'Name': name
}
# Display the extracted segment information
for segment, info in segments_info.items():
print(f"{segment} Info:")
print(f" ID: {info['ID']}")
print(f" LabelValue: {info['LabelValue']}")
print(f" Layer: {info['Layer']}")
print(f" Name: {info['Name']}\n")print_seg_nrrd_info(here("data/MRI-Brain-Eye/Case1/Segmentation.seg.nrrd"))
Segment_0 Info:
ID: Segment_1
LabelValue: 1
Layer: 0
Name: Segment_LE
Segment_1 Info:
ID: Segment_2
LabelValue: 2
Layer: 0
Name: Segment_RE
print_seg_nrrd_info(here("data/MRI-Brain-Eye/Case2/Segmentation_Eye.seg.nrrd"))Segment_0 Info:
ID: Segment_1
LabelValue: 1
Layer: 0
Name: Segment_LE
Segment_1 Info:
ID: Segment_2
LabelValue: 2
Layer: 0
Name: Segment_RE
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 Noneget_labelvalue_by_name(here("data/MRI-Brain-Eye/Case1/Segmentation.seg.nrrd"), "Segment_LE")1
get_labelvalue_by_name(here("data/MRI-Brain-Eye/Case1/Segmentation.seg.nrrd"), "Segment_RE")2