mask.py
13.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
#--------------------------------------------------------------------------
# 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 os
import plistlib
import random
import shutil
import tempfile
import numpy as np
import vtk
import invesalius.constants as const
import invesalius.data.imagedata_utils as iu
import invesalius.session as ses
from . import floodfill
from wx.lib.pubsub import pub as Publisher
from scipy import ndimage
class EditionHistoryNode(object):
def __init__(self, index, orientation, array, clean=False):
self.index = index
self.orientation = orientation
self.filename = tempfile.mktemp(suffix='.npy')
self.clean = clean
self._save_array(array)
def _save_array(self, array):
np.save(self.filename, array)
print "Saving history", self.index, self.orientation, self.filename, self.clean
def commit_history(self, mvolume):
array = np.load(self.filename)
if self.orientation == 'AXIAL':
mvolume[self.index+1,1:,1:] = array
if self.clean:
mvolume[self.index+1, 0, 0] = 1
elif self.orientation == 'CORONAL':
mvolume[1:, self.index+1, 1:] = array
if self.clean:
mvolume[0, self.index+1, 0] = 1
elif self.orientation == 'SAGITAL':
mvolume[1:, 1:, self.index+1] = array
if self.clean:
mvolume[0, 0, self.index+1] = 1
elif self.orientation == 'VOLUME':
mvolume[:] = array
print "applying to", self.orientation, "at slice", self.index
def __del__(self):
print "Removing", self.filename
os.remove(self.filename)
class EditionHistory(object):
def __init__(self, size=50):
self.history = []
self.index = -1
self.size = size * 2
Publisher.sendMessage("Enable undo", False)
Publisher.sendMessage("Enable redo", False)
def new_node(self, index, orientation, array, p_array, clean):
# Saving the previous state, used to undo/redo correctly.
p_node = EditionHistoryNode(index, orientation, p_array, clean)
self.add(p_node)
node = EditionHistoryNode(index, orientation, array, clean)
self.add(node)
def add(self, node):
if self.index == self.size:
self.history.pop(0)
self.index -= 1
if self.index < len(self.history):
self.history = self.history[:self.index + 1]
self.history.append(node)
self.index += 1
print "INDEX", self.index, len(self.history), self.history
Publisher.sendMessage("Enable undo", True)
Publisher.sendMessage("Enable redo", False)
def undo(self, mvolume, actual_slices=None):
h = self.history
if self.index > 0:
#if self.index > 0 and h[self.index].clean:
##self.index -= 1
##h[self.index].commit_history(mvolume)
#self._reload_slice(self.index - 1)
if h[self.index - 1].orientation == 'VOLUME':
self.index -= 1
h[self.index].commit_history(mvolume)
self._reload_slice(self.index)
Publisher.sendMessage("Enable redo", True)
elif actual_slices and actual_slices[h[self.index - 1].orientation] != h[self.index - 1].index:
self._reload_slice(self.index - 1)
else:
self.index -= 1
h[self.index].commit_history(mvolume)
if actual_slices and self.index and actual_slices[h[self.index - 1].orientation] == h[self.index - 1].index:
self.index -= 1
h[self.index].commit_history(mvolume)
self._reload_slice(self.index)
Publisher.sendMessage("Enable redo", True)
if self.index == 0:
Publisher.sendMessage("Enable undo", False)
print "AT", self.index, len(self.history), self.history[self.index].filename
def redo(self, mvolume, actual_slices=None):
h = self.history
if self.index < len(h) - 1:
#if self.index < len(h) - 1 and h[self.index].clean:
##self.index += 1
##h[self.index].commit_history(mvolume)
#self._reload_slice(self.index + 1)
if h[self.index + 1].orientation == 'VOLUME':
self.index += 1
h[self.index].commit_history(mvolume)
self._reload_slice(self.index)
Publisher.sendMessage("Enable undo", True)
elif actual_slices and actual_slices[h[self.index + 1].orientation] != h[self.index + 1].index:
self._reload_slice(self.index + 1)
else:
self.index += 1
h[self.index].commit_history(mvolume)
if actual_slices and self.index < len(h) - 1 and actual_slices[h[self.index + 1].orientation] == h[self.index + 1].index:
self.index += 1
h[self.index].commit_history(mvolume)
self._reload_slice(self.index)
Publisher.sendMessage("Enable undo", True)
if self.index == len(h) - 1:
Publisher.sendMessage("Enable redo", False)
print "AT", self.index, len(h), h[self.index].filename
def _reload_slice(self, index):
Publisher.sendMessage(('Set scroll position', self.history[index].orientation),
self.history[index].index)
def _config_undo_redo(self, visible):
v_undo = False
v_redo = False
if self.history and visible:
v_undo = True
v_redo = True
if self.index == 0:
v_undo = False
elif self.index == len(self.history) - 1:
v_redo = False
Publisher.sendMessage("Enable undo", v_undo)
Publisher.sendMessage("Enable redo", v_redo)
def clear_history(self):
self.history = []
self.index = -1
Publisher.sendMessage("Enable undo", False)
Publisher.sendMessage("Enable redo", False)
class Mask():
general_index = -1
def __init__(self):
Mask.general_index += 1
self.index = Mask.general_index
self.imagedata = ''
self.colour = random.choice(const.MASK_COLOUR)
self.opacity = const.MASK_OPACITY
self.threshold_range = const.THRESHOLD_RANGE
self.name = const.MASK_NAME_PATTERN %(Mask.general_index+1)
self.edition_threshold_range = [const.THRESHOLD_OUTVALUE, const.THRESHOLD_INVALUE]
self.is_shown = 1
self.edited_points = {}
self.was_edited = False
self.__bind_events()
self.history = EditionHistory()
def __bind_events(self):
Publisher.subscribe(self.OnFlipVolume, 'Flip volume')
Publisher.subscribe(self.OnSwapVolumeAxes, 'Swap volume axes')
def save_history(self, index, orientation, array, p_array, clean=False):
self.history.new_node(index, orientation, array, p_array, clean)
def undo_history(self, actual_slices):
self.history.undo(self.matrix, actual_slices)
# Marking the project as changed
session = ses.Session()
session.ChangeProject()
def redo_history(self, actual_slices):
self.history.redo(self.matrix, actual_slices)
# Marking the project as changed
session = ses.Session()
session.ChangeProject()
def on_show(self):
self.history._config_undo_redo(self.is_shown)
def SavePlist(self, dir_temp, filelist):
mask = {}
filename = u'mask_%d' % self.index
mask_filename = u'%s.dat' % filename
mask_filepath = os.path.join(dir_temp, mask_filename)
filelist[self.temp_file] = mask_filename
#self._save_mask(mask_filepath)
mask['index'] = self.index
mask['name'] = self.name
mask['colour'] = self.colour
mask['opacity'] = self.opacity
mask['threshold_range'] = self.threshold_range
mask['edition_threshold_range'] = self.edition_threshold_range
mask['visible'] = self.is_shown
mask['mask_file'] = mask_filename
mask['mask_shape'] = self.matrix.shape
mask['edited'] = self.was_edited
plist_filename = filename + '.plist'
#plist_filepath = os.path.join(dir_temp, plist_filename)
temp_plist = tempfile.mktemp()
plistlib.writePlist(mask, temp_plist)
filelist[temp_plist] = plist_filename
return plist_filename
def OpenPList(self, filename):
mask = plistlib.readPlist(filename)
self.index = mask['index']
self.name = mask['name']
self.colour = mask['colour']
self.opacity = mask['opacity']
self.threshold_range = mask['threshold_range']
self.edition_threshold_range = mask['edition_threshold_range']
self.is_shown = mask['visible']
mask_file = mask['mask_file']
shape = mask['mask_shape']
self.was_edited = mask.get('edited', False)
dirpath = os.path.abspath(os.path.split(filename)[0])
path = os.path.join(dirpath, mask_file)
self._open_mask(path, tuple(shape))
def OnFlipVolume(self, pubsub_evt):
axis = pubsub_evt.data
submatrix = self.matrix[1:, 1:, 1:]
if axis == 0:
submatrix[:] = submatrix[::-1]
self.matrix[1::, 0, 0] = self.matrix[:0:-1, 0, 0]
elif axis == 1:
submatrix[:] = submatrix[:, ::-1]
self.matrix[0, 1::, 0] = self.matrix[0, :0:-1, 0]
elif axis == 2:
submatrix[:] = submatrix[:, :, ::-1]
self.matrix[0, 0, 1::] = self.matrix[0, 0, :0:-1]
def OnSwapVolumeAxes(self, pubsub_evt):
axis0, axis1 = pubsub_evt.data
self.matrix = self.matrix.swapaxes(axis0, axis1)
print type(self.matrix)
def _save_mask(self, filename):
shutil.copyfile(self.temp_file, filename)
def _open_mask(self, filename, shape, dtype='uint8'):
print ">>", filename, shape
self.temp_file = filename
self.matrix = np.memmap(filename, shape=shape, dtype=dtype, mode="r+")
def _set_class_index(self, index):
Mask.general_index = index
def create_mask(self, shape):
"""
Creates a new mask object. This method do not append this new mask into the project.
Parameters:
shape(int, int, int): The shape of the new mask.
"""
self.temp_file = tempfile.mktemp()
shape = shape[0] + 1, shape[1] + 1, shape[2] + 1
self.matrix = np.memmap(self.temp_file, mode='w+', dtype='uint8', shape=shape)
def clean(self):
self.matrix[1:, 1:, 1:] = 0
self.matrix[0, :, :] = 1
self.matrix[:, 0, :] = 1
self.matrix[:, :, 0] = 1
def copy(self, copy_name):
"""
creates and return a copy from the mask instance.
params:
copy_name: the name from the copy
"""
new_mask = Mask()
new_mask.name = copy_name
new_mask.colour = self.colour
new_mask.opacity = self.opacity
new_mask.threshold_range = self.threshold_range
new_mask.edition_threshold_range = self.edition_threshold_range
new_mask.is_shown = self.is_shown
new_mask.create_mask(shape=[i-1 for i in self.matrix.shape])
new_mask.matrix[:] = self.matrix[:]
return new_mask
def clear_history(self):
self.history.clear_history()
def fill_holes_auto(self, target, conn, orientation, index, size):
CON2D = {4: 1, 8: 2}
CON3D = {6: 1, 18: 2, 26: 3}
if target == '3D':
cp_mask = self.matrix.copy()
matrix = self.matrix[1:, 1:, 1:]
bstruct = ndimage.generate_binary_structure(3, CON3D[conn])
imask = (~(matrix > 127))
labels, nlabels = ndimage.label(imask, bstruct, output=np.uint16)
if nlabels == 0:
return
ret = floodfill.fill_holes_automatically(matrix, labels, nlabels, size)
if ret:
self.save_history(index, orientation, self.matrix.copy(), cp_mask)
else:
bstruct = ndimage.generate_binary_structure(2, CON2D[conn])
if orientation == 'AXIAL':
matrix = self.matrix[index+1, 1:, 1:]
elif orientation == 'CORONAL':
matrix = self.matrix[1:, index+1, 1:]
elif orientation == 'SAGITAL':
matrix = self.matrix[1:, 1:, index+1]
cp_mask = matrix.copy()
imask = (~(matrix > 127))
labels, nlabels = ndimage.label(imask, bstruct, output=np.uint16)
if nlabels == 0:
return
labels = labels.reshape(1, labels.shape[0], labels.shape[1])
matrix = matrix.reshape(1, matrix.shape[0], matrix.shape[1])
ret = floodfill.fill_holes_automatically(matrix, labels, nlabels, size)
if ret:
self.save_history(index, orientation, matrix.copy(), cp_mask)
def __del__(self):
if self.is_shown:
self.history._config_undo_redo(False)
os.remove(self.temp_file)