How to load .nii using monai
To load a .nii
or .nii.gz
file using MONAI, you typically use LoadImaged
(for dict-style data) or LoadImage
(for raw image loading).
✅ Option 1: Quick Load with LoadImage
(for single image)
from monai.transforms import LoadImage
loader = LoadImage(image_only=True)
image = loader("path/to/your_image.nii.gz")
print(image.shape)
image_only=True
: returns just the image as a NumPy array or PyTorch tensor.- You can also get metadata (e.g., spacing, affine) by setting
image_only=False
.
✅ Option 2: Pipeline Load with LoadImaged
(for dictionary-based workflows)
This is ideal if you’re working with datasets or training pipelines:
from monai.transforms import LoadImaged, Compose
from monai.data import Dataset
data_dicts = [{"image": "path/to/image.nii.gz"}]
transforms = Compose([
LoadImaged(keys=["image"]),
])
dataset = Dataset(data=data_dicts, transform=transforms)
loaded = dataset[0]["image"]
print(loaded.shape)
🔄 Notes
- MONAI supports both
.nii
and.nii.gz
. - Images are returned as PyTorch tensors, unless
image_only=False
.
🧪 Optional: Get Affine & Metadata
loader = LoadImage(image_only=False)
image, meta = loader("your_image.nii.gz")
print(meta["affine"])
How to read in T1w.mgz using monai
To read a .mgz
file like T1w.mgz
using MONAI, you’ll need to use nibabel
as an intermediate step, because MONAI’s built-in image loaders do not natively support .mgz
files out of the box.
✅ Option 1: Load .mgz
using nibabel
and convert to a PyTorch tensor
import nibabel as nib
import torch
import numpy as np
# Load the .mgz file
img = nib.load("path/to/T1w.mgz")
data = img.get_fdata()
# Convert to torch tensor and add channel dimension (MONAI expects [C, H, W, D])
tensor = torch.tensor(data).unsqueeze(0).float()
print(tensor.shape) # should be [1, H, W, D]
✅ Option 2: Wrap into MONAI Transform Pipeline
You can create a custom transform to use .mgz
files inside a MONAI pipeline:
from monai.transforms import Transform
class LoadMGZ(Transform):
def __call__(self, filename):
img = nib.load(filename)
data = img.get_fdata()
return torch.tensor(data).unsqueeze(0).float()
Then use it like this:
from monai.transforms import Compose
from monai.data import Dataset
data_dicts = [{"image": "path/to/T1w.mgz"}]
transforms = Compose([
LoadMGZ(),
])
dataset = Dataset(data=data_dicts, transform=transforms)
image = dataset[0]["image"]
🧠 Why .mgz
is special
.mgz
is a compressed format used by FreeSurfer, and isn’t natively supported by MONAI’s loaders like LoadImage
. However, nibabel
supports it fully and integrates well with MONAI if you manually handle the conversion.
Discover more from Science Comics
Subscribe to get the latest posts sent to your email.