-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathCILViewer2D.py
1971 lines (1595 loc) · 76.4 KB
/
CILViewer2D.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
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
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
# Copyright 2017 - 2019 Edoardo Pasca
# Copyright 2018 Richard Smith
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import numpy
import vtk
from ccpi.viewer import (ALT_KEY, CONTROL_KEY, SHIFT_KEY, CROSSHAIR_ACTOR, CURSOR_ACTOR, HELP_ACTOR, HISTOGRAM_ACTOR,
LINEPLOT_ACTOR, OVERLAY_ACTOR, SLICE_ACTOR, WIPE_ACTOR, SLICE_ORIENTATION_XY,
SLICE_ORIENTATION_XZ, SLICE_ORIENTATION_YZ)
from ccpi.viewer.CILViewerBase import CILViewerBase
from ccpi.viewer.utils import Converter
from ccpi.viewer.widgets import cilviewerBoxWidget, SliceSliderRepresentation, SliderCallback
class CILInteractorStyle(vtk.vtkInteractorStyle):
def __init__(self, callback):
self.callback = callback
self._viewer = callback
priority = 1.0
self.debug = False
self.AddObserver("MouseWheelForwardEvent", self.OnMouseWheelForward, priority)
self.AddObserver("MouseWheelBackwardEvent", self.OnMouseWheelBackward, priority)
self.AddObserver('KeyPressEvent', self.OnKeyPress, priority)
self.AddObserver('KeyReleaseEvent', self.OnKeyRelease, priority)
self.AddObserver('LeftButtonPressEvent', self.OnLeftButtonPressEvent, priority)
self.AddObserver('RightButtonPressEvent', self.OnRightButtonPressEvent, priority)
self.AddObserver('LeftButtonReleaseEvent', self.OnLeftButtonReleaseEvent, priority)
self.AddObserver('RightButtonReleaseEvent', self.OnRightButtonReleaseEvent, priority)
self.AddObserver('MouseMoveEvent', self.OnMouseMoveEvent, priority)
self.InitialEventPosition = (0, 0)
# Initialise difference from zoom event start point
self.dy = 0
self._reslicing_enabled = True
self.htext = None
@property
def reslicing_enabled(self):
return self._reslicing_enabled
@reslicing_enabled.setter
def reslicing_enabled(self, value):
if isinstance(value, bool):
self._reslicing_enabled = value
def log(self, msg):
if self.debug:
print(msg)
def SetInitialEventPosition(self, xy):
self.InitialEventPosition = xy
def GetInitialEventPosition(self):
return self.InitialEventPosition
def GetKeyCode(self):
return self.GetInteractor().GetKeyCode()
def SetKeyCode(self, keycode):
self.GetInteractor().SetKeyCode(keycode)
def GetControlKey(self):
return self.GetInteractor().GetControlKey()
def GetShiftKey(self):
return self.GetInteractor().GetShiftKey()
def GetAltKey(self):
return self.GetInteractor().GetAltKey()
def GetEventPosition(self):
return self.GetInteractor().GetEventPosition()
def GetDeltaEventPosition(self):
x, y = self.GetInteractor().GetEventPosition()
return (x - self.InitialEventPosition[0], y - self.InitialEventPosition[1])
def Dolly(self, factor):
self.callback.camera.Dolly(factor)
self.callback.ren.ResetCameraClippingRange()
def GetDimensions(self):
return self._viewer.img3D.GetDimensions()
def GetInputData(self):
return self._viewer.img3D
def GetSliceOrientation(self):
return self._viewer.sliceOrientation
def SetSliceOrientation(self, orientation):
self._viewer.sliceOrientation = orientation
def GetActiveSlice(self):
return self._viewer.getActiveSlice()
def SetActiveSlice(self, sliceno):
self._viewer.setActiveSlice(sliceno)
def UpdatePipeline(self, reset=False):
self._viewer.updatePipeline(reset)
def GetActiveCamera(self):
return self._viewer.ren.GetActiveCamera()
def SetActiveCamera(self, camera):
self._viewer.ren.SetActiveCamera(camera)
def ResetCamera(self):
self._viewer.ren.ResetCamera()
def FlipCameraPosition(self, flip=True):
self._viewer.flipCameraPosition = flip
def Render(self):
self._viewer.renWin.Render()
def UpdateImageSlice(self):
self._viewer.imageSlice.Update()
self.AdjustCamera()
self.Render()
def AdjustCamera(self):
self._viewer.AdjustCamera()
def SaveRender(self, filename):
self._viewer.saveRender(filename)
def GetRenderWindow(self):
return self._viewer.renWin
def GetRenderer(self):
return self._viewer.ren
def GetROIWidget(self):
return self._viewer.ROIWidget
def SetEventActive(self, event):
self._viewer.event.On(event)
def SetEventInactive(self, event):
self._viewer.event.Off(event)
def GetViewerEvent(self, event):
return self._viewer.event.isActive(event)
def SetInitialCameraPosition(self, position):
self._viewer.InitialCameraPosition = position
def GetInitialCameraPosition(self):
return self._viewer.InitialCameraPosition
def SetInitialLevel(self, level):
self._viewer.InitialLevel = level
def GetInitialLevel(self):
return self._viewer.InitialLevel
def SetInitialWindow(self, window):
self._viewer.InitialWindow = window
def GetInitialWindow(self):
return self._viewer.InitialWindow
def SetROI(self, roi):
self._viewer.ROI = roi
def GetROI(self):
return self._viewer.ROI
def GetVisualisationDownsampling(self):
return self._viewer.visualisation_downsampling
def SetVisualisationDownsampling(self, value):
self._viewer.setVisualisationDownsampling(value)
def CreateAnnotationText(self, display_type, data):
return self._viewer.createAnnotationText(display_type, data)
def UpdateCornerAnnotation(self, text, corner):
self._viewer.updateCornerAnnotation(text, corner)
def GetPicker(self):
return self._viewer.picker
def GetCornerAnnotation(self):
return self._viewer.cornerAnnotation
def UpdateROIHistogram(self):
self._viewer.updateROIHistogram()
def UpdateLinePlot(self, imagecoordinate, display):
self._viewer.updateLinePlot(imagecoordinate, display)
def GetCrosshairs(self):
actor = self._viewer.crosshairsActor
vert = self._viewer.vertLine
horiz = self._viewer.horizLine
return actor, vert, horiz
def GetImageWorldExtent(self):
"""Deprecated. Use `GetDataExtentInWorld` and `GetMinMaxVoxelsFromExtent`."""
return self.image2world(self.GetInputData().GetExtent()[1::2])
def GetDataExtentInWorld(self):
"""
Compute and return the extent of the input data in the rendered world.
"""
data_extent_image = self.GetInputData().GetExtent()
data_extent_world = self.Image2WorldExtent(data_extent_image)
return data_extent_world
def GetMinMaxVoxelsFromExtent(self, extent):
"""Given the extent of a box or image, gets the voxels corresponding to the min values in all directions
and max values in all directions."""
voxel_min = extent[0::2]
voxel_max = extent[1::2]
return voxel_min, voxel_max
def Image2WorldExtent(self, extent_image):
"""Given the extent of a box or image, gets the voxels corresponding to the min values in all directions
and max values in all directions. Then, converts their coordinates in the world coordinate system.
Returns the converted extent."""
voxel_min_image, voxel_max_image = self.GetMinMaxVoxelsFromExtent(extent_image)
voxel_min_world = self.image2world(voxel_min_image)
voxel_max_world = self.image2world(voxel_max_image)
extent_world = self.GetExtentFromVoxels(voxel_min_world, voxel_max_world)
return extent_world
def GetExtentFromVoxels(self, voxel_min, voxel_max):
"""Given the voxels corresponding to the min values in all directions
and max values in all directions, calculates the extent of the box or image they enclose."""
extent = (voxel_min[0], voxel_max[0], voxel_min[1], voxel_max[1], voxel_min[2], voxel_max[2])
return extent
def SetCharEvent(self, char):
self.GetInteractor().SetKeyCode(char)
self.OnKeyPress(self.GetInteractor(), "KeyPressEvent")
def validateValue(self, value, axis):
return self._viewer.validateValue(value, axis)
def InitialiseBox(self, clickPosition):
"""
Set the initial values for the box borders
:param clickPosition: Display coordinates for the mouse event
"""
box_pos = cilviewerBoxWidget.GetBoxBoundsFromEventPosition(self._viewer, clickPosition)
# Set widget placement and make visible
self._viewer.ROIWidget.PlaceWidget(box_pos)
self._viewer.ROIWidget.On()
self.UpdatePipeline()
############### Handle events
def OnMouseWheelForward(self, interactor, event):
if self.GetInputData() is None:
return
maxSlice = self.GetInputData().GetExtent()[self.GetSliceOrientation() * 2 + 1]
shift = interactor.GetShiftKey()
advance = 1
if shift:
advance = 10
if (self.GetActiveSlice() + advance <= maxSlice):
self.SetActiveSlice(self.GetActiveSlice() + advance)
self.UpdatePipeline()
else:
self.log("maxSlice %d request %d" % (maxSlice, self.GetActiveSlice()))
if self.GetViewerEvent("SHOW_LINE_PROFILE_EVENT"):
self.DisplayLineProfile(interactor, event, True)
def OnMouseWheelBackward(self, interactor, event):
if self.GetInputData() is None:
return
minSlice = self.GetInputData().GetExtent()[self.GetSliceOrientation() * 2]
shift = interactor.GetShiftKey()
advance = 1
if shift:
advance = 10
if (self.GetActiveSlice() - advance >= minSlice):
self.SetActiveSlice(self.GetActiveSlice() - advance)
self.UpdatePipeline()
else:
self.log("minSlice %d request %d" % (minSlice, self.GetActiveSlice()))
if self.GetViewerEvent("SHOW_LINE_PROFILE_EVENT"):
self.DisplayLineProfile(interactor, event, True)
def AutoWindowLevelOnVolumeRange(self, update_slice=True):
'''Auto-adjusts window-level for the slice, based on the 5 and 95th percentiles of the whole image volume.'''
cmin, cmax = self._viewer.getImageMapRange((5., 95.), method="scalar")
print("Auto range for volume: ", cmin, cmax)
window, level = self._viewer.getSliceWindowLevelFromRange(cmin, cmax)
self._viewer.imageSlice.GetProperty().SetColorLevel(level)
self._viewer.imageSlice.GetProperty().SetColorWindow(window)
if update_slice:
self.UpdateImageSlice()
def ChangeOrientation(self, new_slice_orientation):
orientation = self.GetSliceOrientation()
camera = vtk.vtkCamera()
camera.ParallelProjectionOn()
camera.SetFocalPoint(self.GetActiveCamera().GetFocalPoint())
camera.SetPosition(self.GetActiveCamera().GetPosition())
self.SetInitialCameraPosition(self.GetActiveCamera().GetPosition())
camera.SetViewUp(self.GetActiveCamera().GetViewUp())
if new_slice_orientation == SLICE_ORIENTATION_XY:
# Equivalent to pressing z
if orientation == SLICE_ORIENTATION_YZ:
self.FlipCameraPosition(True)
camera.Elevation(90)
elif orientation == SLICE_ORIENTATION_XZ:
camera.Elevation(-90)
self.FlipCameraPosition(True)
camera.SetViewUp(0, -1, 0)
elif new_slice_orientation == SLICE_ORIENTATION_XZ:
# Equivalent to pressing y
if orientation == SLICE_ORIENTATION_XY:
camera.Elevation(90)
self.FlipCameraPosition(True)
elif orientation == SLICE_ORIENTATION_YZ:
camera.Azimuth(90)
camera.SetViewUp(0, 0, -1)
elif new_slice_orientation == SLICE_ORIENTATION_YZ:
# Equivalent to pressing x
if orientation == SLICE_ORIENTATION_XY:
camera.Azimuth(270)
elif orientation == SLICE_ORIENTATION_XZ:
self.FlipCameraPosition(True)
camera.Azimuth(90)
camera.SetViewUp(0, 0, -1)
self.SetActiveCamera(camera)
self.SetSliceOrientation(new_slice_orientation)
self.UpdatePipeline(True)
def OnKeyPress(self, interactor, event):
al = self._viewer.axisLabelsText
if self.GetInputData() is None:
return
if self.reslicing_enabled and interactor.GetKeyCode() == "x":
self._viewer.setAxisLabels(['', al[1], al[2]], False)
self.ChangeOrientation(SLICE_ORIENTATION_YZ)
elif self.reslicing_enabled and interactor.GetKeyCode() == "y":
self._viewer.setAxisLabels([al[0], '', al[2]], False)
self.ChangeOrientation(SLICE_ORIENTATION_XZ)
elif self.reslicing_enabled and interactor.GetKeyCode() == "z":
self._viewer.setAxisLabels([al[0], al[1], ''], False)
self.ChangeOrientation(SLICE_ORIENTATION_XY)
elif interactor.GetKeyCode() == "a":
self._viewer.autoWindowLevelOnSliceRange()
elif interactor.GetKeyCode() == "s":
filename = "current_render"
self.SaveRender(filename)
elif interactor.GetKeyCode() == "q":
self.log("Render loop terminating by pressing %s" % (interactor.GetKeyCode(), ))
interactor.SetKeyCode("e")
self.OnKeyPress(interactor, event)
elif interactor.GetKeyCode() == "l":
if self.GetViewerEvent("SHOW_LINE_PROFILE_EVENT"):
self.SetEventInactive("SHOW_LINE_PROFILE_EVENT")
self.DisplayLineProfile(interactor, event, False)
else:
self.SetEventActive("SHOW_LINE_PROFILE_EVENT")
self.DisplayLineProfile(interactor, event, True)
elif interactor.GetKeyCode() == "h":
self.DisplayHelp()
elif interactor.GetKeyCode() == "w":
self.SetEventActive('UPDATE_WINDOW_LEVEL_UNDER_CURSOR')
elif interactor.GetKeyCode() == "t":
# tracing event is captured by widget
if (self._viewer.imageTracer.GetEnabled()):
self._viewer.imageTracer.Off()
else:
self._viewer.imageTracer.On()
elif interactor.GetKeyCode() == "i":
# toggle interpolation of slice actor
is_interpolated = self._viewer.imageSlice.GetProperty().GetInterpolationType()
if is_interpolated:
self._viewer.imageSlice.GetProperty().SetInterpolationTypeToNearest()
else:
self._viewer.imageSlice.GetProperty().SetInterpolationTypeToLinear()
self._viewer.updatePipeline()
elif interactor.GetKeyCode() == '1':
ev = 'RECTILINEAR_WIPE'
if self.GetViewerEvent(ev):
self.SetEventInactive(ev)
# ImageWithOverlay
self._viewer.setVisualisationToImageWithOverlay()
self.AdjustCamera()
self.Render()
elif interactor.GetKeyCode() == '2':
if self._viewer.image2 is not None:
if self._viewer.vis_mode != CILViewer2D.RECTILINEAR_WIPE:
self._viewer.setVisualisationToRectilinearWipe()
orient = ['x', 'y', 'z']
self.SetCharEvent(orient[self.GetSliceOrientation()])
self.SetEventActive('RECTILINEAR_WIPE')
else:
self.log("Unhandled event %s" % (interactor.GetKeyCode()))
def OnKeyRelease(self, interactor, event):
# remove events on key release
events = ['UPDATE_WINDOW_LEVEL_UNDER_CURSOR']
for ev in events:
if self.GetViewerEvent(ev):
# print ("remove event {}".format(ev))
self.SetEventInactive(ev)
def RemoveROIWidget(self):
self.SetEventActive("DELETE_ROI_EVENT")
self.GetROIWidget().Off()
self._viewer.updateCornerAnnotation("", 1, False)
self.SetDisplayHistogram(False)
self.Render()
def OnLeftButtonPressEvent(self, interactor, event):
# print ("INTERACTOR", interactor)
if self.GetInputData() is None:
return
alt = interactor.GetAltKey()
shift = interactor.GetShiftKey()
ctrl = interactor.GetControlKey()
self.SetInitialEventPosition(interactor.GetEventPosition())
if ctrl and not (alt and shift):
self.SetEventActive("CREATE_ROI_EVENT")
position = interactor.GetEventPosition()
self.InitialiseBox(position)
self.SetDisplayHistogram(True)
self.Render()
self.log("Event %s is CREATE_ROI_EVENT" % (event))
elif alt and not (shift and ctrl):
self.RemoveROIWidget()
self.log("Event %s is DELETE_ROI_EVENT" % (event))
elif not (ctrl and alt and shift):
self.SetEventActive("PICK_EVENT")
self.HandlePickEvent(interactor, event)
self.log("Event %s is PICK_EVENT" % (event))
def SetDisplayHistogram(self, display):
if display:
if (self._viewer.displayHistogram == 0):
#self.GetRenderer().AddActor(self._viewer.histogramPlotActor)
self._viewer.AddActor(self._viewer.histogramPlotActor, HISTOGRAM_ACTOR)
self.firstHistogram = 1
self.Render()
self._viewer.histogramPlotActor.VisibilityOn()
self._viewer.displayHistogram = True
else:
self._viewer.histogramPlotActor.VisibilityOff()
self._viewer.displayHistogram = False
def OnLeftButtonReleaseEvent(self, interactor, event):
interactor = self._viewer.getInteractor()
if self.GetViewerEvent("CREATE_ROI_EVENT"):
self.OnROIModifiedEvent(interactor, event)
elif self.GetViewerEvent("PICK_EVENT"):
self.HandlePickEvent(interactor, event)
# Turn off CREATE_ROI and PICK_EVENT
self.SetEventInactive("CREATE_ROI_EVENT")
self.SetEventInactive("PICK_EVENT")
self.SetEventInactive("DELETE_ROI_EVENT")
def OnRightButtonPressEvent(self, interactor, event):
if self.GetInputData() is None:
return
alt = interactor.GetAltKey()
shift = interactor.GetShiftKey()
ctrl = interactor.GetControlKey()
self.SetInitialEventPosition(interactor.GetEventPosition())
if alt and not (ctrl and shift):
self.SetEventActive("WINDOW_LEVEL_EVENT")
if self._viewer.vis_mode == CILViewer2D.IMAGE_WITH_OVERLAY:
self.log("Event %s is WINDOW_LEVEL_EVENT" % (event))
self.HandleWindowLevel(interactor, event)
elif shift and not (ctrl and alt):
self.SetEventActive("ZOOM_EVENT")
self.SetInitialCameraPosition(self.GetActiveCamera().GetPosition())
self.log("Event %s is ZOOM_EVENT" % (event))
elif ctrl and not (shift and alt):
self.SetEventActive("PAN_EVENT")
self.SetInitialCameraPosition(self.GetActiveCamera().GetPosition())
self.log("Event %s is PAN_EVENT" % (event))
def OnRightButtonReleaseEvent(self, interactor, event):
self.log(event)
if self.GetViewerEvent("WINDOW_LEVEL_EVENT"):
if self._viewer.vis_mode == CILViewer2D.IMAGE_WITH_OVERLAY:
self.SetInitialLevel(self._viewer.imageSlice.GetProperty().GetColorLevel())
self.SetInitialWindow(self._viewer.imageSlice.GetProperty().GetColorWindow())
elif self.GetViewerEvent("ZOOM_EVENT") or self.GetViewerEvent("PAN_EVENT"):
self.SetInitialCameraPosition(())
# Reset difference from start of zoom event
self.dy = 0
# self.SetViewerEvent( ViewerEvent.NO_EVENT )
self.SetEventInactive("WINDOW_LEVEL_EVENT")
self.SetEventInactive("ZOOM_EVENT")
self.SetEventInactive("PAN_EVENT")
def BoxExtentCheck(self, box_extent_world):
box_voxel_min, box_voxel_max = self.GetMinMaxVoxelsFromExtent(box_extent_world)
box_voxel_min = list(box_voxel_min)
box_voxel_max = list(box_voxel_max)
# Get maximum extents of the image in world coords
data_extent = self.GetDataExtentInWorld()
voxel_min_world, voxel_max_world = self.GetMinMaxVoxelsFromExtent(data_extent)
i = [self.GetSliceOrientation()]
i.extend([(i[0] + 1) % 3, (i[0] + 2) % 3])
if box_voxel_min[i[1]] < voxel_min_world[i[1]]:
box_voxel_min[i[1]] = voxel_min_world[i[1]]
if box_voxel_min[i[2]] < voxel_min_world[i[2]]:
box_voxel_min[i[2]] = voxel_min_world[i[2]]
if box_voxel_max[i[1]] > voxel_max_world[i[1]]:
box_voxel_max[i[1]] = voxel_max_world[i[1]]
if box_voxel_max[i[2]] > voxel_max_world[i[2]]:
box_voxel_max[i[2]] = voxel_max_world[i[2]]
box_extent_world = self.GetExtentFromVoxels(box_voxel_min, box_voxel_max)
return box_extent_world
def GetBoxWidgetExtentInWorld(self, box_widget):
''' Returns the extent of a box_widget (vtkBoxWidget)
which is present on the viewer, in the image coordinate system.'''
pd = vtk.vtkPolyData()
box_widget.GetPolyData(pd)
box_extent_world = pd.GetBounds()
return box_extent_world
def GetBoxWidgetExtentInImage(self, box_widget):
''' Returns the extent of a box_widget (vtkBoxWidget)
which is present on the viewer, in the image coordinate system.'''
pd = vtk.vtkPolyData()
box_widget.GetPolyData(pd)
box_extent_world = pd.GetBounds()
box_voxel_min_world, box_voxel_max_world = self.GetMinMaxVoxelsFromExtent(box_extent_world)
box_voxel_min_image = self.createVox(box_voxel_min_world)
box_voxel_max_image = self.createVox(box_voxel_max_world)
box_extent_image = self.GetExtentFromVoxels(box_voxel_min_image, box_voxel_max_image)
return box_extent_image
def OnROIModifiedEvent(self, interactor, event):
# Get bounds from 3D ROI
pd = vtk.vtkPolyData()
self.GetROIWidget().GetPolyData(pd)
bounds = pd.GetBounds()
# Get maximum extents of the image in world coords
bounds = self.BoxExtentCheck(bounds)
self._viewer.ROIWidget.PlaceWidget(bounds)
data_extent = self.GetDataExtentInWorld()
#self._viewer.ROIWidget.On()
#self.UpdatePipeline()
voxel_min_world, voxel_max_world = self.GetMinMaxVoxelsFromExtent(data_extent)
vox1 = self.createVox(voxel_min_world)
vox2 = self.createVox(voxel_max_world)
# Set the ROI using image coordinates
self.SetROI((vox1, vox2))
roi = self.GetROI()
# Debug messages
self.log("ROI {0}".format(roi))
self.log("Pixel1 %d,%d,%d Value %f" % vox1)
self.log("Pixel2 %d,%d,%d Value %f" % vox2)
# Calculate the size of the ROI
if self.GetSliceOrientation() == SLICE_ORIENTATION_XY:
self.log("slice orientation : XY")
x = abs(roi[1][0] - roi[0][0])
y = abs(roi[1][1] - roi[0][1])
z = abs(roi[1][2] - roi[0][2])
elif self.GetSliceOrientation() == SLICE_ORIENTATION_XZ:
self.log("slice orientation : XZ")
x = abs(roi[1][0] - roi[0][0])
y = abs(roi[1][2] - roi[0][2])
z = abs(roi[1][1] - roi[0][1])
elif self.GetSliceOrientation() == SLICE_ORIENTATION_YZ:
self.log("slice orientation : YZ")
x = abs(roi[1][1] - roi[0][1])
y = abs(roi[1][2] - roi[0][2])
z = abs(roi[1][1] - roi[0][1])
# Update the text bottom right of the viewer and histogram
roi_data = (x, y, z, float(x * y) / 1024.)
text = self.CreateAnnotationText("roi", roi_data)
self.log(text)
self.UpdateCornerAnnotation(text, 1)
self.UpdateROIHistogram()
# self.SetViewerEvent( ViewerEvent.NO_EVENT )
self.SetEventInactive("CREATE_ROI_EVENT")
def OnTracerModifiedEvent(self, interactor, event):
# Makes sure tracer is visible on current slice:
self.UpdatePipeline()
########################### Coordinate conversion methods ############################
def display2world(self, displayCoords):
"""
Takes display coordinates and converts them into world coordinates
:param displayCoords: tuple containing the X,Y coordinates for the point in the display
:return: The computed world coordinate of the given point as double (x,y,z)
"""
coord = vtk.vtkCoordinate()
coord.SetCoordinateSystemToDisplay()
coord.SetValue(displayCoords[0], displayCoords[1])
return coord.GetComputedWorldValue(self.GetRenderer())
def world2display(self, world_coords):
"""
Takes coordinates in the world system and converts them to 2D display coordinates
:param world_coords: (x,y,z) coordinate in the world
:return: (x,y) screen coordinate
"""
vc = vtk.vtkCoordinate()
vc.SetCoordinateSystemToWorld()
vc.SetValue(world_coords)
return vc.GetComputedDoubleDisplayValue(self.GetRenderer())
def display2imageCoordinate(self, viewerposition, subvoxel=False):
"""
Convert display coordinates into image coordinates and add the pixel value
:param viewerposition: (x,y) position of the selected point in the display window
:return: (x,y,z,a) x,y,z index of the selected slice + a, the pixel value
"""
vc = vtk.vtkCoordinate()
vc.SetCoordinateSystemToViewport()
vc.SetValue(viewerposition[0:2] + (0.0, ))
pickPosition = list(vc.GetComputedWorldValue(self.GetRenderer()))
# print ("PICK POS", pickPosition)
pickPosition[self.GetSliceOrientation()] = \
self.GetInputData().GetSpacing()[self.GetSliceOrientation()] * (self.GetActiveSlice()) # + self.GetInputData().GetOrigin()[self.GetSliceOrientation()])
self.log("Pick Position " + str(pickPosition))
if (pickPosition != [0, 0, 0]):
imagePosition = self.world2imageCoordinate(pickPosition)
imagePositionF = self.world2imageCoordinateFloat(pickPosition)
extent = self._viewer.img3D.GetExtent()
# make sure the pick is on the image
if imagePosition[0] < extent[0]:
imagePosition[0] = extent[0]
if imagePosition[0] > extent[1]:
imagePosition[0] = extent[1]
if imagePosition[1] < extent[2]:
imagePosition[1] = extent[2]
if imagePosition[1] > extent[3]:
imagePosition[1] = extent[3]
if imagePosition[2] < extent[4]:
imagePosition[2] = extent[4]
if imagePosition[2] > extent[5]:
imagePosition[2] = extent[5]
self.log("imagePosition pre validate {}".format(imagePosition))
pixelValue = self.GetInputData().GetScalarComponentAsDouble(imagePosition[0], imagePosition[1],
imagePosition[2], 0)
if self._viewer.rescale[0]:
scale, shift = self._viewer.rescale[1]
# pix = orig * scale + shift
# orig = (-shift + pix) / scale
pixelValue = (-shift + pixelValue) / scale
if subvoxel:
for i in range(3):
if not i == self.GetSliceOrientation():
imagePosition[i] = imagePositionF[i]
return (self.validateValue(imagePosition[0], 'x'), self.validateValue(imagePosition[1], 'y'),
self.validateValue(imagePosition[2], 'z'), pixelValue)
else:
return (0, 0, 0, 0)
def createVox(self, world_coordinates):
# Translate the world coordinates to an image index
imagePosition = self.world2imageCoordinate(world_coordinates)
pixelValue = self.GetInputData().GetScalarComponentAsDouble(imagePosition[0], imagePosition[1],
imagePosition[2], 0)
if self._viewer.rescale[0]:
scale, shift = self._viewer.rescale[1]
pixelValue = (-shift + pixelValue) / scale
return (self.validateValue(imagePosition[0],
'x'), self.validateValue(imagePosition[1],
'y'), self.validateValue(imagePosition[2], 'z'), pixelValue)
def world2imageCoordinate(self, world_coordinates):
"""
Convert from the world or global coordinates to image coordinates
:param world_coordinates: (x,y,z)
:return: rounded to next integer (x,y,z) in image coorindates eg. slice index
"""
dims = self.GetInputData().GetDimensions()
self.log(dims)
spac = self.GetInputData().GetSpacing()
orig = self.GetInputData().GetOrigin()
return [round((world_coordinates[i]) / spac[i] - orig[i]) for i in range(3)]
def world2imageCoordinateFloat(self, world_coordinates):
"""
Convert from the world or global coordinates to image coordinates
:param world_coordinates: (x,y,z)
:return: float (x,y,z) in image coorindates eg. slice index
"""
dims = self.GetInputData().GetDimensions()
self.log(dims)
spac = self.GetInputData().GetSpacing()
orig = self.GetInputData().GetOrigin()
return [(world_coordinates[i]) / spac[i] - orig[i] for i in range(3)]
def image2world(self, image_coordinates):
spac = self.GetInputData().GetSpacing()
orig = self.GetInputData().GetOrigin()
return [(image_coordinates[i]) * spac[i] + orig[i] for i in range(3)]
def imageCoordinate2display(self, imageposition):
'''
Convert image coordinates back into viewer coordinates
:param imageposition: (x,y,z) coordinates in image coordinates
:return: (x,y,z) coordinates for the window
'''
# Truncate to first 3 values x,y,z. Not interested in pixel value.
ip = imageposition[0:3]
spac = self.GetInputData().GetSpacing()
orig = self.GetInputData().GetOrigin()
# Convert image coordiantes to world coordinates
world_coord = [spac[i] * (ip[i] - orig[i]) for i in range(3)]
vc = vtk.vtkCoordinate()
vc.SetCoordinateSystemToWorld()
vc.SetValue(world_coord)
return vc.GetComputedDoubleViewportValue(self.GetRenderer())
def display2normalisedViewport(self, display_coords):
wsize = self.GetRenderWindow().GetSize()
x = display_coords[0] / wsize[0]
y = display_coords[1] / wsize[1]
return x, y
def OnMouseMoveEvent(self, interactor, event):
if self.GetInputData() is not None:
if self.GetViewerEvent("WINDOW_LEVEL_EVENT"):
self.log("Event %s is WINDOW_LEVEL_EVENT" % (event))
self.HandleWindowLevel(interactor, event)
elif self.GetViewerEvent("PICK_EVENT"):
self.HandlePickEvent(interactor, event)
elif self.GetViewerEvent("ZOOM_EVENT"):
self.HandleZoomEvent(interactor, event)
elif self.GetViewerEvent("PAN_EVENT"):
self.HandlePanEvent(interactor, event)
elif self.GetViewerEvent("SHOW_LINE_PROFILE_EVENT"):
self.DisplayLineProfile(interactor, event, True)
elif self.GetViewerEvent('UPDATE_WINDOW_LEVEL_UNDER_CURSOR'):
x, y = interactor.GetEventPosition()
ic = self.display2imageCoordinate((x, y))
print(x, y, ic, "image coordinate")
whole_extent = self._viewer.img3D.GetExtent()
around = numpy.min(numpy.asarray([whole_extent[1], whole_extent[3], whole_extent[5]])) // 10
print(around, "around")
extent = [
ic[0] - around, ic[0] + around, ic[1] - around, ic[1] + around, ic[2] - around, ic[2] + around
]
orientation = self._viewer.sliceOrientation
extent[orientation * 2] = self.GetActiveSlice()
extent[orientation * 2 + 1] = self.GetActiveSlice()
if extent[0] < whole_extent[0]:
extent[0] = whole_extent[0]
if extent[1] > whole_extent[1]:
extent[1] = whole_extent[1]
if extent[2] < whole_extent[2]:
extent[2] = whole_extent[2]
if extent[3] > whole_extent[3]:
extent[3] = whole_extent[3]
if extent[4] < whole_extent[4]:
extent[4] = whole_extent[4]
if extent[5] > whole_extent[5]:
extent[5] = whole_extent[5]
# get mouse location
print(*extent, "w extent")
self._viewer.voicursor.SetInputData(self._viewer.img3D)
self._viewer.voicursor.SetVOI(*extent)
self._viewer.voicursor.Update()
# set window/level for current slices
self._viewer.iacursor.SetInputConnection(self._viewer.voicursor.GetOutputPort())
self._viewer.iacursor.SetAutoRangePercentiles(1.0, 99.)
self._viewer.iacursor.Update()
# reset color/window
cmin, cmax = self._viewer.iacursor.GetAutoRange()
window, level = self._viewer.getSliceWindowLevelFromRange(cmin, cmax)
self.SetInitialLevel(level)
self.SetInitialWindow(window)
self._viewer.imageSlice.GetProperty().SetColorLevel(self.GetInitialLevel())
self._viewer.imageSlice.GetProperty().SetColorWindow(self.GetInitialWindow())
self.UpdateImageSlice()
elif self.GetViewerEvent('RECTILINEAR_WIPE'):
# get event in image coordinate
x, y, z, pix = self.display2imageCoordinate(interactor.GetEventPosition())
# update the wipe depending on the slice orientation
slice_orientation = self._viewer.getSliceOrientation()
if slice_orientation == SLICE_ORIENTATION_XY:
self._viewer.wipe.SetAxis(0, 1)
self._viewer.wipe.SetPosition(x, y)
elif slice_orientation == SLICE_ORIENTATION_XZ:
self._viewer.wipe.SetAxis(0, 2)
self._viewer.wipe.SetPosition(x, z)
elif slice_orientation == SLICE_ORIENTATION_YZ:
self._viewer.wipe.SetAxis(2, 1)
self._viewer.wipe.SetPosition(z, y)
self.UpdatePipeline()
def DisplayHelp(self):
help_actor = self._viewer.helpActor
image_slice = self._viewer.imageSlice
if help_actor.GetVisibility():
help_actor.VisibilityOff()
image_slice.VisibilityOn()
self.Render()
return
font_size = 16
# Create the text mappers and the associated Actor2Ds.
# The font and text properties (except justification) are the same for
# each multi line mapper. Let's create a common text property object
multiLineTextProp = vtk.vtkTextProperty()
multiLineTextProp.SetFontSize(font_size)
multiLineTextProp.SetFontFamilyToArial()
multiLineTextProp.BoldOn()
multiLineTextProp.ItalicOn()
multiLineTextProp.ShadowOn()
multiLineTextProp.SetLineSpacing(1.3)
# The text is on multiple lines and center-justified (both horizontal and
# vertical).
textMapperC = vtk.vtkTextMapper()
if self.htext == None:
self.htext = """
Mouse Interactions:
- Slice: Mouse Scroll
- Quick Slice: Shift + Mouse Scroll
- Pick: Left Click
- Zoom: Shift + Right Mouse + Move Up/Down
- Pan: Ctrl + Right Mouse + Move
- Adjust Window: Alt+ Right Mouse + Move Up/Down
- Adjust Level: Alt + Right Mouse + Move Left/Right
Region of Interest (ROI):
- Create: Ctrl + Left Click
- Delete: Alt + Left Click
- Resize: Click + Drag handles
- Translate: Middle Mouse + Move within ROI
Keyboard Interactions:
h: This help
x: YZ Plane
y: XZ Plane
z: XY Plane
a: Whole image Auto Window/Level
w: Region around cursor Auto Window/Level
l: Line Profile at cursor
s: Save Current Image
t: Tracing
i: Toggle interpolation of slice
"""
textMapperC.SetInput(self.htext)
tprop = textMapperC.GetTextProperty()
tprop.ShallowCopy(multiLineTextProp)
tprop.SetJustificationToLeft()
tprop.SetVerticalJustificationToCentered()
tprop.SetColor(0, 1, 0)
help_actor.SetMapper(textMapperC)
help_actor.VisibilityOn()
image_slice.VisibilityOff()
self.Render()
def HandleZoomEvent(self, interactor, event):
camera = self.GetActiveCamera()
# Extract change from start of event
dx, dy = interactor.GetDeltaEventPosition()
window_y_size = self.GetRenderWindow().GetSize()[1]
# Determine whether the user is zooming in or out
change = dy - self.dy
# Make sure that a change has been registered
if change != 0:
# >1 zoom in, <1 zoom out
camera.Zoom(1 + change / window_y_size)
self.Render()
# Set the overall change value
self.dy = dy
def HandlePanEvent(self, interactor, event):
#Camera uses world coordinates, not display coordinates so we have to make a coneversion
interactor_event_position = interactor.GetEventPosition()
interactor_initial_event_position = interactor.GetInitialEventPosition()
event_position = interactor.image2world(interactor.display2imageCoordinate(interactor_event_position)[:-1])
initial_event_position = interactor.image2world(
interactor.display2imageCoordinate(interactor_initial_event_position)[:-1])
#Update initial position to current event position, ready for next panning event:
interactor.SetInitialEventPosition(interactor_event_position)
change = []
for i in range(len(event_position)):
change.append(event_position[i] - initial_event_position[i])
camera = self.GetActiveCamera()
newposition = [i for i in self.GetInitialCameraPosition()]
newfocalpoint = [i for i in camera.GetFocalPoint()]
for i in range(len(event_position)):
newposition[i] -= change[i]
newfocalpoint[i] -= change[i]