imagedata_utils.py
12.9 KB
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
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
#--------------------------------------------------------------------------
# Software: InVesalius - Software de Reconstrucao 3D de Imagens Medicas
# Copyright: (C) 2001 Centro de Pesquisas Renato Archer
# Homepage: http://www.softwarepublico.gov.br
# Contact: invesalius@cti.gov.br
# License: GNU - GPL 2 (LICENSE.txt/LICENCA.txt)
#--------------------------------------------------------------------------
# Este programa e software livre; voce pode redistribui-lo e/ou
# modifica-lo sob os termos da Licenca Publica Geral GNU, conforme
# publicada pela Free Software Foundation; de acordo com a versao 2
# da Licenca.
#
# Este programa eh distribuido na expectativa de ser util, mas SEM
# QUALQUER GARANTIA; sem mesmo a garantia implicita de
# COMERCIALIZACAO ou de ADEQUACAO A QUALQUER PROPOSITO EM
# PARTICULAR. Consulte a Licenca Publica Geral GNU para obter mais
# detalhes.
#--------------------------------------------------------------------------
import math
import os
import vtk
import vtkgdcm
import wx.lib.pubsub as ps
import constants as const
from data import vtk_utils
import utils
# TODO: Test cases which are originally in sagittal/coronal orientation
# and have gantry
def ResampleImage3D(imagedata, value):
"""
Resample vtkImageData matrix.
"""
spacing = imagedata.GetSpacing()
extent = imagedata.GetExtent()
size = imagedata.GetDimensions()
width = float(size[0])
height = float(size[1]/value)
resolution = (height/(extent[1]-extent[0])+1)*spacing[1]
resample = vtk.vtkImageResample()
resample.SetInput(imagedata)
resample.SetAxisMagnificationFactor(0, resolution)
resample.SetAxisMagnificationFactor(1, resolution)
return resample.GetOutput()
def ResampleImage2D(imagedata, px, py,
update_progress = None):
"""
Resample vtkImageData matrix.
"""
extent = imagedata.GetExtent()
spacing = imagedata.GetSpacing()
#if extent[1]==extent[3]:
# f = extent[1]
#elif extent[1]==extent[5]:
# f = extent[1]
#elif extent[3]==extent[5]:
# f = extent[3]
if abs(extent[1]-extent[3]) < abs(extent[3]-extent[5]):
f = extent[1]
elif abs(extent[1]-extent[5]) < abs(extent[1] - extent[3]):
f = extent[1]
elif abs(extent[3]-extent[5]) < abs(extent[1] - extent[3]):
f = extent[3]
else:
f = extent[1]
factor_x = px/float(f+1)
factor_y = py/float(f+1)
resample = vtk.vtkImageResample()
resample.SetInput(imagedata)
resample.SetAxisMagnificationFactor(0, factor_x)
resample.SetAxisMagnificationFactor(1, factor_y)
resample.SetOutputSpacing(spacing[0] * factor_x, spacing[1] * factor_y, spacing[2])
if (update_progress):
message = _("Generating multiplanar visualization...")
resample.AddObserver("ProgressEvent", lambda obj,
evt:update_progress(resample,message))
resample.Update()
return resample.GetOutput()
def FixGantryTilt(imagedata, tilt):
"""
Fix gantry tilt given a vtkImageData and the tilt value. Return new
vtkImageData.
"""
# Retrieve data from original imagedata
extent = [int(value) for value in imagedata.GetExtent()]
origin = imagedata.GetOrigin()
spacing = [float(value) for value in imagedata.GetSpacing()]
n_slices = int(extent[5])
new_zspacing = math.cos(tilt*(math.acos(-1.0)/180.0)) * spacing[2] #zspacing
translate_coef = math.tan(tilt*math.pi/180.0)*new_zspacing*(n_slices-1)
# Class responsible for translating data
reslice = vtk.vtkImageReslice()
reslice.SetInput(imagedata)
reslice.SetInterpolationModeToLinear()
# Translation will create new pixels. Let's set new pixels' colour to black.
reslice.SetBackgroundLevel(imagedata.GetScalarRange()[0])
# Class responsible for append translated data
append = vtk.vtkImageAppend()
append.SetAppendAxis(2)
# Translate and append each slice
for i in xrange(n_slices+1):
slice_imagedata = vtk.vtkImageData()
value = math.tan(tilt*math.pi/180.0) * new_zspacing * i
new_origin1 = origin[1] + value - translate_coef
# Translate data
reslice.SetOutputOrigin(origin[0], new_origin1, origin[2])
reslice.SetOutputExtent(extent[0], extent[1], extent[2], extent[3], i,i)
reslice.Update()
# Append data
slice_imagedata.DeepCopy(reslice.GetOutput())
slice_imagedata.UpdateInformation()
append.AddInput(slice_imagedata)
append.Update()
# Final imagedata
imagedata = vtk.vtkImageData()
imagedata.DeepCopy(append.GetOutput())
imagedata.SetSpacing(spacing[0], spacing[1], new_zspacing)
imagedata.SetExtent(extent)
imagedata.UpdateInformation()
return imagedata
def BuildEditedImage(imagedata, points):
"""
Editing the original image in accordance with the edit
points in the editor, it is necessary to generate the
vtkPolyData via vtkContourFilter
"""
for point in points:
x, y, z = point
colour = points[point]
imagedata.SetScalarComponentFromDouble(x, y, z, 0, colour)
imagedata.Update()
return imagedata
def Export(imagedata, filename, bin=False):
writer = vtk.vtkXMLImageDataWriter()
writer.SetFileName(filename)
if bin:
writer.SetDataModeToBinary()
else:
writer.SetDataModeToAscii()
writer.SetInput(imagedata)
writer.Write()
def Import(filename):
reader = vtk.vtkXMLImageDataReader()
reader.SetFileName(filename)
# TODO: Check if the code bellow is necessary
reader.WholeSlicesOn()
reader.Update()
return reader.GetOutput()
def View(imagedata):
viewer = vtk.vtkImageViewer()
viewer.SetInput(imagedata)
viewer.SetColorWindow(200)
viewer.SetColorLevel(100)
viewer.Render()
import time
time.sleep(10)
def ViewGDCM(imagedata):
viewer = vtkgdcm.vtkImageColorViewer()
viewer.SetInput(reader.GetOutput())
viewer.SetColorWindow(500.)
viewer.SetColorLevel(50.)
viewer.Render()
import time
time.sleep(5)
def ExtractVOI(imagedata,xi,xf,yi,yf,zi,zf):
"""
Cropping the vtkImagedata according
with values.
"""
voi = vtk.vtkExtractVOI()
voi.SetVOI(xi,xf,yi,yf,zi,zf)
voi.SetInput(imagedata)
voi.SetSampleRate(1, 1, 1)
voi.Update()
return voi.GetOutput()
def CreateImageData(filelist, zspacing, size, bits):
message = _("Generating multiplanar visualization...")
if not const.VTK_WARNING:
log_path = os.path.join(const.LOG_FOLDER, 'vtkoutput.txt')
fow = vtk.vtkFileOutputWindow()
fow.SetFileName(log_path)
ow = vtk.vtkOutputWindow()
ow.SetInstance(fow)
x,y = size
px, py = utils.PredictingMemory(len(filelist), x, y, bits)
utils.debug("Image Resized to >>> %f x %f" % (px, py))
if (x == px) and (y == py):
const.REDUCE_IMAGEDATA_QUALITY = 0
else:
const.REDUCE_IMAGEDATA_QUALITY = 1
if not(const.REDUCE_IMAGEDATA_QUALITY):
update_progress= vtk_utils.ShowProgress(1, dialog_type = "ProgressDialog")
array = vtk.vtkStringArray()
for x in xrange(len(filelist)):
array.InsertValue(x,filelist[x])
reader = vtkgdcm.vtkGDCMImageReader()
reader.SetFileNames(array)
reader.AddObserver("ProgressEvent", lambda obj,evt:
update_progress(reader,message))
reader.Update()
# The zpacing is a DicomGroup property, so we need to set it
imagedata = vtk.vtkImageData()
imagedata.DeepCopy(reader.GetOutput())
spacing = imagedata.GetSpacing()
imagedata.SetSpacing(spacing[0], spacing[1], zspacing)
else:
update_progress= vtk_utils.ShowProgress(2*len(filelist),
dialog_type = "ProgressDialog")
# Reformat each slice and future append them
appender = vtk.vtkImageAppend()
appender.SetAppendAxis(2) #Define Stack in Z
# Reformat each slice
for x in xrange(len(filelist)):
# TODO: We need to check this automatically according
# to each computer's architecture
# If the resolution of the matrix is too large
reader = vtkgdcm.vtkGDCMImageReader()
reader.SetFileName(filelist[x])
reader.AddObserver("ProgressEvent", lambda obj,evt:
update_progress(reader,message))
reader.Update()
#Resample image in x,y dimension
slice_imagedata = ResampleImage2D(reader.GetOutput(), px, py, update_progress)
#Stack images in Z axes
appender.AddInput(slice_imagedata)
#appender.AddObserver("ProgressEvent", lambda obj,evt:update_progress(appender))
appender.Update()
# The zpacing is a DicomGroup property, so we need to set it
imagedata = vtk.vtkImageData()
imagedata.DeepCopy(appender.GetOutput())
spacing = imagedata.GetSpacing()
imagedata.SetSpacing(spacing[0], spacing[1], zspacing)
imagedata.AddObserver("ProgressEvent", lambda obj,evt:
update_progress(imagedata,message))
imagedata.Update()
return imagedata
class ImageCreator:
def __init__(self):
self.running = True
ps.Publisher().subscribe(self.CancelImageDataLoad, "Cancel DICOM load")
def CancelImageDataLoad(self, evt_pusub):
utils.debug("Canceling")
self.running = False
def CreateImageData(self, filelist, zspacing, size, bits):
message = _("Generating multiplanar visualization...")
if not const.VTK_WARNING:
log_path = os.path.join(const.LOG_FOLDER, 'vtkoutput.txt')
fow = vtk.vtkFileOutputWindow()
fow.SetFileName(log_path)
ow = vtk.vtkOutputWindow()
ow.SetInstance(fow)
x,y = size
px, py = utils.PredictingMemory(len(filelist), x, y, bits)
utils.debug("Image Resized to >>> %f x %f" % (px, py))
if (x == px) and (y == py):
const.REDUCE_IMAGEDATA_QUALITY = 0
else:
const.REDUCE_IMAGEDATA_QUALITY = 1
if not(const.REDUCE_IMAGEDATA_QUALITY):
update_progress= vtk_utils.ShowProgress(1, dialog_type = "ProgressDialog")
array = vtk.vtkStringArray()
for x in xrange(len(filelist)):
if not self.running:
return False
array.InsertValue(x,filelist[x])
if not self.running:
return False
reader = vtkgdcm.vtkGDCMImageReader()
reader.SetFileNames(array)
reader.AddObserver("ProgressEvent", lambda obj,evt:
update_progress(reader,message))
reader.Update()
if not self.running:
reader.AbortExecuteOn()
return False
# The zpacing is a DicomGroup property, so we need to set it
imagedata = vtk.vtkImageData()
imagedata.DeepCopy(reader.GetOutput())
spacing = imagedata.GetSpacing()
imagedata.SetSpacing(spacing[0], spacing[1], zspacing)
else:
update_progress= vtk_utils.ShowProgress(2*len(filelist),
dialog_type = "ProgressDialog")
# Reformat each slice and future append them
appender = vtk.vtkImageAppend()
appender.SetAppendAxis(2) #Define Stack in Z
# Reformat each slice
for x in xrange(len(filelist)):
# TODO: We need to check this automatically according
# to each computer's architecture
# If the resolution of the matrix is too large
if not self.running:
return False
reader = vtkgdcm.vtkGDCMImageReader()
reader.SetFileName(filelist[x])
reader.AddObserver("ProgressEvent", lambda obj,evt:
update_progress(reader,message))
reader.Update()
#Resample image in x,y dimension
slice_imagedata = ResampleImage2D(reader.GetOutput(), px, py, update_progress)
#Stack images in Z axes
appender.AddInput(slice_imagedata)
#appender.AddObserver("ProgressEvent", lambda obj,evt:update_progress(appender))
appender.Update()
# The zpacing is a DicomGroup property, so we need to set it
if not self.running:
return False
imagedata = vtk.vtkImageData()
imagedata.DeepCopy(appender.GetOutput())
spacing = imagedata.GetSpacing()
imagedata.SetSpacing(spacing[0], spacing[1], zspacing)
imagedata.AddObserver("ProgressEvent", lambda obj,evt:
update_progress(imagedata,message))
imagedata.Update()
return imagedata