Datasets:

ArXiv:
License:

Mismatched NIfTI Headers of Image and the Merged Mask

#2
by YongchengYAO - opened

Issue:

mismatched nii.gz header between the image (ct.nii.gz) and the corresponding merged mask file (combined_labels.nii.gz)

  • most (maybe all) of them are the mismatch in the translation part of the affine matrix
    e.g.
Mismatch in affine between image and mask:
Image affine:
[[  -0.777    0.       0.     191.9  ]
 [   0.      -0.777    0.     156.4  ]
 [   0.       0.       2.5   -717.75 ]
 [   0.       0.       0.       1.   ]]
Mask affine:
[[-0.777  0.     0.    -0.   ]
 [ 0.    -0.777  0.    -0.   ]
 [ 0.     0.     2.5    0.   ]
 [ 0.     0.     0.     1.   ]]

Why does it matter?

Visualization
A mismatched NIfTI header would render the image and mask misaligned in visualization software like ITK-SNAP and VScode NiiVue plugin.
Spatial Information
For measurement/quantification purposes, it is very important that the spatial information of the segmentation mask matches that of the image.

Solution

You could notify users about the issue and request them to update the mask file header to match the image file’s header. Alternatively, we could update the dataset.
Thanks.

Code for downloading the dataset and moving files to Images and Masks:

# Download dataset
dest_dir = "Images-raw"
snapshot_download(
    repo_id="AbdomenAtlas/AbdomenAtlas1.0Mini",
    repo_type="dataset",
    local_dir=dest_dir,
)

# Create Images and Masks directories
os.makedirs("Images", exist_ok=True)
os.makedirs("Masks", exist_ok=True)

# Process each case folder
for case_dir in glob.glob(os.path.join(dest_dir, "BDMAP*")):
    if os.path.isdir(case_dir):
        case_name = os.path.basename(case_dir)

        # Move CT images
        ct_src = os.path.join(case_dir, "ct.nii.gz")
        if os.path.exists(ct_src):
            shutil.move(ct_src, os.path.join("Images", f"{case_name}.nii.gz"))

        # Move mask files
        mask_src = os.path.join(case_dir, "combined_labels.nii.gz")
        if os.path.exists(mask_src):
            shutil.move(mask_src, os.path.join("Masks", f"{case_name}.nii.gz"))

# Clean up the raw directory
shutil.rmtree(dest_dir)
if os.path.exists(".cache"):
    shutil.rmtree(".cache")

Code for checking the file header:

import os
import glob
import numpy as np
import nibabel as nib


def check_nii_header_for_img_mask(image_path, mask_path):
    # Inspect the mask files
    mask_nii = nib.load(mask_path)
    mask_data = mask_nii.get_fdata()
    mask_file_info = {
        "voxel_size": tuple(round(x, 3) for x in mask_nii.header.get_zooms()),
        "affine": np.round(mask_nii.affine, 3),
        "orientation": nib.orientations.aff2axcodes(mask_nii.affine),
        "array_size": mask_data.shape,
    }
    # Inspect the image files
    img_nii = nib.load(image_path)
    img_data = img_nii.get_fdata()
    image_file_info = {
        "voxel_size": tuple(round(x, 3) for x in img_nii.header.get_zooms()),
        "affine": np.round(img_nii.affine, 3),
        "orientation": nib.orientations.aff2axcodes(img_nii.affine),
        "array_size": img_data.shape,
    }
    # Check if mask and image properties match
    print(
        f"Checking properties for the image and mask images:\nImage: {image_path}\nMask: {mask_path}"
    )
    for key in mask_file_info:
        if isinstance(mask_file_info[key], np.ndarray):
            if not np.allclose(
                mask_file_info[key], image_file_info[key], atol=1e-5, rtol=1e-3
            ):
                raise ValueError(
                    f"\n\nMismatch in {key} between image and mask:\n"
                    f"Image {key}:\n{image_file_info[key]}\n"
                    f"Mask {key}:\n{mask_file_info[key]}\n"
                )
        elif mask_file_info[key] != image_file_info[key]:
            raise ValueError(
                f"\n\nMismatch in {key} between image and mask:\n"
                f"Image {key}:\n{image_file_info[key]}\n"
                f"Mask {key}:\n{mask_file_info[key]}\n"
            )
    print(f"Properties (NIfTI file header) match!\n")


def check_nii_header_for_img_mask_batch(image_dir, mask_dir):
    """
    Check NIfTI headers for all matching image and mask pairs in given directories

    Args:
        image_dir (str): Directory containing image files
        mask_dir (str): Directory containing mask files
    """
    # Get all nii.gz files in image directory
    image_files = glob.glob(os.path.join(image_dir, "*.nii.gz"))
    total_files = len(image_files)

    print(f"Found {total_files} image files. Starting header check...\n")

    for idx, image_path in enumerate(image_files, 1):
        # Get corresponding mask file name
        image_name = os.path.basename(image_path)
        mask_path = os.path.join(mask_dir, image_name)

        print(f"Processing file {idx}/{total_files}")

        # Check if mask exists
        if not os.path.exists(mask_path):
            print(f"WARNING: No matching mask found for {image_name}\n")
            continue

        try:
            check_nii_header_for_img_mask(image_path, mask_path)
        except ValueError as e:
            print(f"ERROR: {str(e)}")
            continue
        except Exception as e:
            print(f"ERROR: Unexpected error processing {image_name}: {str(e)}\n")
            continue

    print("\nHeader check completed for all files!")


check_nii_header_for_img_mask_batch("Images", "Masks")
Your need to confirm your account before you can post a new comment.

Sign up or log in to comment