forked from SlicerDMRI/SlicerDMRI
-
Notifications
You must be signed in to change notification settings - Fork 0
/
NIfTIFile.py
183 lines (139 loc) · 5.21 KB
/
NIfTIFile.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
import logging
import os
import unittest
import vtk, qt, ctk, slicer
from slicer.ScriptedLoadableModule import *
class NIfTIFile(ScriptedLoadableModule):
def __init__(self, parent):
ScriptedLoadableModule.__init__(self, parent)
parent.title = 'NIfTIFile'
parent.categories = ['Testing.TestCases']
parent.dependencies = []
parent.contributors = ["Steve Pieper (Isomics)", ]
parent.helpText = '''
This module is used to implement diffusion nifti reading and writing using the conversion tool from PNL at BWH.
'''
parent.acknowledgementText = '''
Thanks to:
Billah, Tashrif; Bouix; Sylvain; Rathi, Yogesh; Various MRI Conversion Tools, https://github.com/pnlbwh/conversion, 2019, DOI: 10.5281/zenodo.2584003
Supported by NIH Grant 5R01MH119222
'''
self.parent = parent
def _NIfTIFileInstallPackage():
try:
import conversion
except ModuleNotFoundError:
slicer.util.pip_install("git+https://github.com/pnlbwh/conversion.git@v2.3")
class NIfTIFileWidget(ScriptedLoadableModuleWidget):
def setup(self):
ScriptedLoadableModuleWidget.setup(self)
# Default reload&test widgets are enough.
# Note that reader and writer is not reloaded.
class NIfTIFileFileReader(object):
def __init__(self, parent):
self.parent = parent
def description(self):
return 'NIfTI Diffusion'
def fileType(self):
return 'NIfTI'
def extensions(self):
return ['NIfTI (*.nii.gz)']
def canLoadFile(self, filePath):
# assume yes if it ends in .nii.gz
# TODO: check for .bval and .bvec in same directory
return True
def load(self, properties):
"""
uses properties:
fileName - path to the .nii.gz file
name (optional) - name for the loaded node
bval (optional) - path to the bval file, defaults to match fileName
bvec (optional)- path to the bvec file, defaults to match fileName
"""
try:
_NIfTIFileInstallPackage()
import conversion
import nibabel
import numpy
filePath = properties['fileName']
# Get node base name from filename
if 'name' in properties.keys():
baseName = properties['name']
else:
baseName = os.path.splitext(os.path.basename(filePath))[0]
baseName = slicer.mrmlScene.GenerateUniqueName(baseName)
diffusionNode = slicer.mrmlScene.AddNewNodeByClass('vtkMRMLDiffusionWeightedVolumeNode', baseName)
measurementFrame = vtk.vtkMatrix4x4()
measurementFrame.Identity()
measurementFrame.SetElement(0,0,-1)
measurementFrame.SetElement(1,1,-1)
diffusionNode.SetMeasurementFrameMatrix(measurementFrame)
niftiImage = nibabel.load(filePath)
affine = niftiImage.affine
ijkToRAS = vtk.vtkMatrix4x4()
for row in range(4):
for column in range(4):
ijkToRAS.SetElement(row, column, affine[row][column])
diffusionNode.SetIJKToRASMatrix(ijkToRAS)
fdata = niftiImage.get_fdata()
diffusionArray = numpy.transpose(fdata, axes=[2,1,0,3])
diffusionImage = vtk.vtkImageData()
dshape = diffusionArray.shape
diffusionImage.SetDimensions(dshape[2],dshape[1],dshape[0])
diffusionImage.AllocateScalars(vtk.VTK_FLOAT, dshape[3])
diffusionNode.SetAndObserveImageData(diffusionImage)
nodeArray = slicer.util.arrayFromVolume(diffusionNode)
nodeArray[:] = diffusionArray
slicer.util.arrayFromVolumeModified(diffusionNode)
pathBase = filePath[:-len(".nii.gz")]
bvalPath = f"{pathBase}.bval"
bvecPath = f"{pathBase}.bvec"
bval = conversion.bval_bvec_io.read_bvals(bvalPath)
bvec = conversion.bval_bvec_io.read_bvecs(bvecPath)
diffusionNode.SetNumberOfGradients(len(bval))
for index in range(len(bval)):
diffusionNode.SetBValue(index, bval[index])
diffusionNode.SetDiffusionGradient(index, bvec[index])
diffusionNode.CreateDefaultDisplayNodes()
except Exception as e:
logging.error('Failed to load file: '+str(e))
import traceback
traceback.print_exc()
return False
self.parent.loadedNodes = [diffusionNode.GetID()]
return True
class NIfTIFileFileWriter(object):
def __init__(self, parent):
self.parent = parent
def description(self):
return 'NIfTI Diffusion'
def fileType(self):
return 'NIfTI'
def extensions(self, obj):
return ['NIfTI (*.nii.gz)']
def canWriteObject(self, obj):
# Only enable this writer in testing mode
if not slicer.app.testingEnabled():
return False
return bool(obj.IsA("vtkMRMLDiffusionWeightedVolumeNode"))
def write(self, properties):
return Fale
class NIfTIFileTest(ScriptedLoadableModuleTest):
def runTest(self):
"""Run as few or as many tests as needed here.
"""
self.setUp()
self.test_Writer()
self.test_Reader()
self.tearDown()
self.delayDisplay('Testing complete')
def setUp(self):
self.tempDir = slicer.util.tempDirectory()
slicer.mrmlScene.Clear()
def tearDown(self):
import shutil
shutil.rmtree(self.tempDir, True)
def test_WriterReader(self):
# Writer and reader tests are put in the same function to ensure
# that writing is done before reading (it generates input data for reading).
# TODO: rewrite this for NIfTI