Reputation: 77
I am looking to convert ~1000 .nrrd
files into Nifit (.nii.gz
) format. I've been using 3DSlicer's ResampleScalarVectorDWIVolume
command-line module to accomplish this task. But this process is really slow. It takes ~4 minutes to convert each file on my system.
I was wondering what tool do people use for such conversions?
Upvotes: 1
Views: 8817
Reputation: 561
Similar to avi.ks's answer, but in case anyone needs to preserve the header information:
import glob
import nibabel as nib
import nrrd
# Get a list of .nrrd files in a directory
nrrd_files = glob.glob('path/to/nrrd/directory/*.nrrd')
# Loop through each .nrrd file
for nrrd_file in nrrd_files:
# Read the .nrrd file
data, header = nrrd.read(nrrd_file)
# Create a NIfTI1Image object
nifti_img = nib.Nifti1Image(data, affine=None)
# Update the NIfTI header with necessary information
nifti_img.header.set_data_dtype(data.dtype)
nifti_img.header.set_zooms(header['space directions'])
# Generate the output .nii file path by replacing the extension
nii_file = nrrd_file.replace('.nrrd', '.nii')
# Save the NIfTI1Image object as .nii file
nib.save(nifti_img, nii_file)
In this code, I use header['space directions']
from the .nrrd header to set the pixel spacing in the NIfTI header using nifti_img.header.set_zooms()
. You might need to adjust the header['spcace direction']
dimension. In my case I change it to :
nifti_img.header.set_zooms([header['space directions'][0, 0],
header['space directions'][1, 1],
header['space directions'][2, 2]])
Upvotes: 0
Reputation: 71
import vtk
def readnrrd(filename):
"""Read image in nrrd format."""
reader = vtk.vtkNrrdReader()
reader.SetFileName(filename)
reader.Update()
info = reader.GetInformation()
return reader.GetOutput(), info
def writenifti(image,filename, info):
"""Write nifti file."""
writer = vtk.vtkNIFTIImageWriter()
writer.SetInputData(image)
writer.SetFileName(filename)
writer.SetInformation(info)
writer.Write()
m, info = readnrrd('/media/neubias/b0c7dd3a-8b12-435e-8303-2c331d05b365/DATA/Henry_data/mri.nrrd')
writenifti(m, '/media/neubias/b0c7dd3a-8b12-435e-8303-2c331d05b365/DATA/Henry_data/mri_prueba2.nii', info)
Upvotes: 7
Reputation: 77
The following code can be used for converting all the '.nrrd' files in a folder into compressed 'nifti' format:
import os
from glob import glob
import nrrd #pip install pynrrd, if pynrrd is not already installed
import nibabel as nib #pip install nibabel, if nibabel is not already installed
import numpy as np
baseDir = os.path.normpath('path/to/file')
files = glob(baseDir+'/*.nrrd')
for file in files:
#load nrrd
_nrrd = nrrd.read(file)
data = _nrrd[0]
header = _nrrd[1]
#save nifti
img = nib.Nifti1Image(data, np.eye(4))
nib.save(img,os.path.join(baseDir, file[-8:-5] + '.nii.gz'))
For example, this script would convert abc.nrrd
and xyz.nrrd
files in the baseDir
to abc.nii.gz
and xyz.nii.gz
respectively.
Upvotes: 4