SoFunction
Updated on 2025-03-01

Read and write to nii format images using Nibabel library

Because the main research direction in the later stage is medical image processing, and most of the data at hand is nii format or HDR or IG format data, the first step is to solve the problem of reading and writing images.

In fact, using OpenCV can also facilitate image reading, but here we will only learn the Nibabel library. If you have time, we will study the use of OpenCV in python.

Nibabel installation

Can be installed via pip

pip install nibabel

Simple image reading and storage operations

import os
import nibabel as nib

# Read the imagepath='C:\Users\Darren\Desktop\'
img=(path)
# View the length, width and height of the image
# Affine transformation of images
# Save the imagepath_save='C:\Users\Darren\Desktop\example_save.'

img.to_filename(path_save)
or
(img,path_save)

Supplementary knowledge:Notes on reading NII format 3D images using SimpleITK

SimpleITK

SimpleITK in Python is widely used in medical image processing tasks and is very powerful, but you still need to pay attention to the dimension when using it, especially when reading images.

Read images in NII format

#Read and display NII image filesfrom matplotlib import pyplot as plt
import SimpleITK as sitk

img_path = ''
I = (img_path)
img = (I)
(img[1,...], cmap='gray', interpolation='bicubic')
([]), ([]) and Y axis
()

The above code is very simple, and I won't explain it much. Add it to the end

print()

If the output (300, 200, 120), it represents the size of the three-dimensional volume data on the Z-axis, Y-axis, and X-axis, which is a bit different from MATLAB and ImageJ, you must pay attention to subsequent processing.

The above article using the Nibabel library to read and write images in nii format is all the content I share with you. I hope you can give you a reference and I hope you can support me more.