Nrrd到Nifti文件转换

时间:2017-12-11 21:02:45

标签: python nifti

我希望将~1000 .nrrd个文件转换为Nifit(.nii.gz)格式。我一直在使用3DSlicerResampleScalarVectorDWIVolume命令行模块来完成此任务。但这个过程非常缓慢。转换系统上的每个文件大约需要4分钟。 我想知道人们使用什么工具进行此类转换?

2 个答案:

答案 0 :(得分:2)

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)

答案 1 :(得分:0)

以下代码可用于将文件夹中的所有“.nrrd”文件转换为压缩的“nifti”格式:

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'))

例如,此脚本会将abc.nrrd中的xyz.nrrdbaseDir文件分别转换为abc.nii.gzxyz.nii.gz