File: vtk_utils.py

package info (click to toggle)
invesalius 3.1.99992-3
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 86,416 kB
  • sloc: python: 28,433; makefile: 56
file content (282 lines) | stat: -rw-r--r-- 9,889 bytes parent folder | download
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
#--------------------------------------------------------------------------
# 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 sys

import vtk
import wx
from wx.lib.pubsub import pub as Publisher
import invesalius.constants as const
from invesalius.gui.dialogs import ProgressDialog

# If you are frightened by the code bellow, or think it must have been result of
# an identation error, lookup at:
# Closures in Python (pt)
# http://devlog.waltercruz.com/closures
# http://montegasppa.blogspot.com/2007/01/tampinhas.html
# Closures not only in Python (en)
# http://en.wikipedia.org/wiki/Closure_%28computer_science%29
# http://www.ibm.com/developerworks/library/l-prog2.html
# http://jjinux.blogspot.com/2006/10/python-modifying-counter-in-closure.html

def ShowProgress(number_of_filters = 1,
                 dialog_type="GaugeProgress"):
    """
    To use this closure, do something like this:
        UpdateProgress = ShowProgress(NUM_FILTERS)
        UpdateProgress(vtkObject)
    """
    progress = [0]
    last_obj_progress = [0]
    if (dialog_type == "ProgressDialog"):
        try:
            dlg = ProgressDialog(100)
        except wx._core.PyNoAppError:
            return lambda obj, label: 0


    # when the pipeline is larger than 1, we have to consider this object
    # percentage
    if number_of_filters < 1:
        number_of_filters = 1
    ratio = (100.0 / number_of_filters)

    def UpdateProgress(obj, label=""):
        """
        Show progress on GUI according to pipeline execution.
        """
        # object progress is cummulative and is between 0.0 - 1.0
        # is necessary verify in case is sending the progress
        #represented by number in case multiprocess, not vtk object
        if isinstance(obj, float) or isinstance(obj, int):
            obj_progress = obj
        else:
            obj_progress = obj.GetProgress()

        # as it is cummulative, we need to compute the diference, to be
        # appended on the interface
        if obj_progress < last_obj_progress[0]: # current obj != previous obj
            difference = obj_progress # 0
        else: # current obj == previous obj
            difference = obj_progress - last_obj_progress[0]

        last_obj_progress[0] = obj_progress

        # final progress status value
        progress[0] = progress[0] + ratio*difference
        # Tell GUI to update progress status value
        if (dialog_type == "GaugeProgress"):
            Publisher.sendMessage('Update status in GUI', value=progress[0], label=label)
        else:
            if (progress[0] >= 99.999):
                progress[0] = 100

            if not(dlg.Update(progress[0],label)):
                dlg.Close()

        return progress[0]

    return UpdateProgress

class Text(object):
    def __init__(self):

        property = vtk.vtkTextProperty()
        property.SetFontSize(const.TEXT_SIZE)
        property.SetFontFamilyToArial()
        property.BoldOff()
        property.ItalicOff()
        property.ShadowOn()
        property.SetJustificationToLeft()
        property.SetVerticalJustificationToTop()
        property.SetColor(const.TEXT_COLOUR)
        self.property = property

        mapper = vtk.vtkTextMapper()
        mapper.SetTextProperty(property)
        self.mapper = mapper

        actor = vtk.vtkActor2D()
        actor.SetMapper(mapper)
        actor.GetPositionCoordinate().SetCoordinateSystemToNormalizedDisplay()
        actor.PickableOff()
        self.actor = actor

        self.SetPosition(const.TEXT_POS_LEFT_UP)

    def SetColour(self, colour):
        self.property.SetColor(colour)

    def ShadowOff(self):
        self.property.ShadowOff()

    def BoldOn(self):
        self.property.BoldOn()

    def SetSize(self, size):
        self.property.SetFontSize(size)

    def SetValue(self, value):
        if isinstance(value, int) or isinstance(value, float):
            value = str(value)
            if sys.platform == 'win32':
                value += "" # Otherwise 0 is not shown under win32
        # With some encoding in some dicom fields (like name) raises a
        # UnicodeEncodeError because they have non-ascii characters. To avoid
        # that we encode in utf-8.
        if sys.platform == 'win32':
            self.mapper.SetInput(value.encode("utf-8"))
        else:
            try:
                self.mapper.SetInput(value.encode("latin-1"))
            except(UnicodeEncodeError):
                self.mapper.SetInput(value.encode("utf-8"))

    def SetCoilDistanceValue(self, value):
        if isinstance(value, int) or isinstance(value, float):
            value = 'Dist: ' + str("{:06.2f}".format(value)) + ' mm'
            if sys.platform == 'win32':
                value += ""  # Otherwise 0 is not shown under win32
                # With some encoding in some dicom fields (like name) raises a
                # UnicodeEncodeError because they have non-ascii characters. To avoid
                # that we encode in utf-8.

        if sys.platform == 'win32':
            self.mapper.SetInput(value.encode("utf-8"))
        else:
            try:
                self.mapper.SetInput(value.encode("latin-1"))
            except(UnicodeEncodeError):
                self.mapper.SetInput(value.encode("utf-8"))

    def SetPosition(self, position):
        self.actor.GetPositionCoordinate().SetValue(position[0],
                                                    position[1])

    def GetPosition(self, position):
        self.actor.GetPositionCoordinate().GetValue()

    def SetJustificationToRight(self):
        self.property.SetJustificationToRight()

    def SetJustificationToCentered(self):
        self.property.SetJustificationToCentered()


    def SetVerticalJustificationToBottom(self):
        self.property.SetVerticalJustificationToBottom()

    def SetVerticalJustificationToCentered(self):
        self.property.SetVerticalJustificationToCentered()

    def Show(self, value=1):
        if value:
            self.actor.VisibilityOn()
        else:
            self.actor.VisibilityOff()

    def Hide(self):
        self.actor.VisibilityOff()

class TextZero(object):
    def __init__(self):

        property = vtk.vtkTextProperty()
        property.SetFontSize(const.TEXT_SIZE_LARGE)
        property.SetFontFamilyToArial()
        property.BoldOn()
        property.ItalicOff()
        #property.ShadowOn()
        property.SetJustificationToLeft()
        property.SetVerticalJustificationToTop()
        property.SetColor(const.TEXT_COLOUR)
        self.property = property

        actor = vtk.vtkTextActor()
        actor.GetTextProperty().ShallowCopy(property)
        actor.GetPositionCoordinate().SetCoordinateSystemToNormalizedDisplay()
        actor.PickableOff()
        self.actor = actor

        self.text = ''
        self.position = (0, 0)
        self.symbolic_syze = wx.FONTSIZE_MEDIUM

    def SetColour(self, colour):
        self.property.SetColor(colour)

    def ShadowOff(self):
        self.property.ShadowOff()

    def SetSize(self, size):
        self.property.SetFontSize(size)

    def SetSymbolicSize(self, size):
        self.symbolic_syze = size

    def SetValue(self, value):
        if isinstance(value, int) or isinstance(value, float):
            value = str(value)
            if sys.platform == 'win32':
                value += "" # Otherwise 0 is not shown under win32
        # With some encoding in some dicom fields (like name) raises a
        # UnicodeEncodeError because they have non-ascii characters. To avoid
        # that we encode in utf-8.
        self.actor.SetInput(value.encode("cp1252"))
        self.text = value

    def SetPosition(self, position):
        self.position = position
        self.actor.GetPositionCoordinate().SetValue(position[0],
                                                    position[1])

    def GetPosition(self):
        return self.actor.GetPositionCoordinate().GetValue()

    def SetJustificationToRight(self):
        self.property.SetJustificationToRight()

    def SetJustificationToCentered(self):
        self.property.SetJustificationToCentered()


    def SetVerticalJustificationToBottom(self):
        self.property.SetVerticalJustificationToBottom()

    def SetVerticalJustificationToCentered(self):
        self.property.SetVerticalJustificationToCentered()

    def Show(self, value=1):
        if value:
            self.actor.VisibilityOn()
        else:
            self.actor.VisibilityOff()

    def Hide(self):
        self.actor.VisibilityOff()

    def draw_to_canvas(self, gc, canvas):
        coord = vtk.vtkCoordinate()
        coord.SetCoordinateSystemToNormalizedDisplay()
        coord.SetValue(*self.position)
        x, y = coord.GetComputedDisplayValue(canvas.evt_renderer)

        font = wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT)
        #  font.SetWeight(wx.FONTWEIGHT_BOLD)
        font.SetSymbolicSize(self.symbolic_syze)
        canvas.draw_text(self.text, (x, y), font=font)