forked from SimpleITK/TUTORIAL
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gui.py
1528 lines (1374 loc) · 61.7 KB
/
gui.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
import SimpleITK as sitk
import matplotlib.pyplot as plt
import ipywidgets as widgets
from IPython.display import display
import numpy as np
from matplotlib.widgets import RectangleSelector
import matplotlib.patches as patches
import matplotlib.cm as cm
from matplotlib.ticker import MaxNLocator
import copy
class RegistrationPointDataAquisition(object):
"""
This class provides a GUI for localizing corresponding points in two images, and for evaluating registration results using a linked cursor
approach, user clicks in one image and the corresponding point is added to the other image.
"""
def __init__(
self,
fixed_image,
moving_image,
fixed_window_level=None,
moving_window_level=None,
figure_size=(10, 8),
known_transformation=None,
):
self.fixed_image = fixed_image
(
self.fixed_npa,
self.fixed_min_intensity,
self.fixed_max_intensity,
) = self.get_window_level_numpy_array(self.fixed_image, fixed_window_level)
self.moving_image = moving_image
(
self.moving_npa,
self.moving_min_intensity,
self.moving_max_intensity,
) = self.get_window_level_numpy_array(self.moving_image, moving_window_level)
self.fixed_point_indexes = []
self.moving_point_indexes = []
self.click_history = (
[]
) # Keep a history of user point localizations, enabling undo of last localization.
self.known_transformation = known_transformation # If the transformation is valid (not None) then corresponding points are automatically added.
self.text_and_marker_color = "red"
ui = self.create_ui()
display(ui)
# Create a figure with two axes for the fixed and moving images.
self.fig, axes = plt.subplots(1, 2, figsize=figure_size)
# self.fig.canvas.set_window_title('Registration Points Acquisition')
self.fixed_axes = axes[0]
self.moving_axes = axes[1]
# Connect the mouse button press to the canvas (__call__ method is the invoked callback).
self.fig.canvas.mpl_connect("button_press_event", self)
# Display the data and the controls, first time we display the images is outside the "update_display" method
# as that method relies on the previous zoom factor which doesn't exist yet.
self.fixed_axes.imshow(
self.fixed_npa[self.fixed_slider.value, :, :]
if self.fixed_slider
else self.fixed_npa,
cmap=plt.cm.Greys_r,
vmin=self.fixed_min_intensity,
vmax=self.fixed_max_intensity,
)
self.moving_axes.imshow(
self.moving_npa[self.moving_slider.value, :, :]
if self.moving_slider
else self.moving_npa,
cmap=plt.cm.Greys_r,
vmin=self.moving_min_intensity,
vmax=self.moving_max_intensity,
)
self.update_display()
def create_ui(self):
# Create the active UI components. Height and width are specified in 'em' units. This is
# a html size specification, size relative to current font size.
self.viewing_checkbox = widgets.RadioButtons(
description="Interaction mode:", options=["edit", "view"], value="edit"
)
self.clearlast_button = widgets.Button(
description="Clear Last", width="7em", height="3em"
)
self.clearlast_button.on_click(self.clear_last)
self.clearall_button = widgets.Button(
description="Clear All", width="7em", height="3em"
)
self.clearall_button.on_click(self.clear_all)
# Sliders are only created if a 3D image, otherwise no need.
self.fixed_slider = self.moving_slider = None
if self.fixed_npa.ndim == 3:
self.fixed_slider = widgets.IntSlider(
description="fixed image z slice:",
min=0,
max=self.fixed_npa.shape[0] - 1,
step=1,
value=int((self.fixed_npa.shape[0] - 1) / 2),
width="20em",
)
self.fixed_slider.observe(self.on_slice_slider_value_change, names="value")
self.moving_slider = widgets.IntSlider(
description="moving image z slice:",
min=0,
max=self.moving_npa.shape[0] - 1,
step=1,
value=int((self.moving_npa.shape[0] - 1) / 2),
width="19em",
)
self.moving_slider.observe(self.on_slice_slider_value_change, names="value")
bx0 = widgets.Box(
padding=7, children=[self.fixed_slider, self.moving_slider]
)
# Layout of UI components. This is pure ugliness because we are not using a UI toolkit. Layout is done
# using the box widget and padding so that the visible UI components are spaced nicely.
bx1 = widgets.Box(padding=7, children=[self.viewing_checkbox])
bx2 = widgets.Box(padding=15, children=[self.clearlast_button])
bx3 = widgets.Box(padding=15, children=[self.clearall_button])
return (
widgets.HBox(children=[widgets.HBox(children=[bx1, bx2, bx3]), bx0])
if self.fixed_npa.ndim == 3
else widgets.HBox(children=[widgets.HBox(children=[bx1, bx2, bx3])])
)
def get_window_level_numpy_array(self, image, window_level):
"""
Get the numpy array representation of the image and the min and max of the intensities
used for display.
"""
npa = sitk.GetArrayViewFromImage(image)
if not window_level:
return npa, npa.min(), npa.max()
else:
return (
npa,
window_level[1] - window_level[0] / 2.0,
window_level[1] + window_level[0] / 2.0,
)
def on_slice_slider_value_change(self, change):
self.update_display()
def update_display(self):
"""
Display the two images based on the slider values, if relevant, and the points which are on the
displayed slices.
"""
# We want to keep the zoom factor which was set prior to display, so we log it before
# clearing the axes.
fixed_xlim = self.fixed_axes.get_xlim()
fixed_ylim = self.fixed_axes.get_ylim()
moving_xlim = self.moving_axes.get_xlim()
moving_ylim = self.moving_axes.get_ylim()
# Draw the fixed image in the first subplot and the localized points.
self.fixed_axes.clear()
self.fixed_axes.imshow(
self.fixed_npa[self.fixed_slider.value, :, :]
if self.fixed_slider
else self.fixed_npa,
cmap=plt.cm.Greys_r,
vmin=self.fixed_min_intensity,
vmax=self.fixed_max_intensity,
)
# Positioning the text is a bit tricky, we position relative to the data coordinate system, but we
# want to specify the shift in pixels as we are dealing with display. We therefore (a) get the data
# point in the display coordinate system in pixel units (b) modify the point using pixel offset and
# transform back to the data coordinate system for display.
text_x_offset = -10
text_y_offset = -10
for i, pnt in enumerate(self.fixed_point_indexes):
if (
self.fixed_slider and int(pnt[2] + 0.5) == self.fixed_slider.value
) or not self.fixed_slider:
self.fixed_axes.scatter(
pnt[0], pnt[1], s=90, marker="+", color=self.text_and_marker_color
)
# Get point in pixels.
text_in_data_coords = self.fixed_axes.transData.transform(
[pnt[0], pnt[1]]
)
# Offset in pixels and get in data coordinates.
text_in_data_coords = self.fixed_axes.transData.inverted().transform(
(
text_in_data_coords[0] + text_x_offset,
text_in_data_coords[1] + text_y_offset,
)
)
self.fixed_axes.text(
text_in_data_coords[0],
text_in_data_coords[1],
str(i),
color=self.text_and_marker_color,
)
self.fixed_axes.set_title(
"fixed image - localized {0} points".format(len(self.fixed_point_indexes))
)
self.fixed_axes.set_axis_off()
# Draw the moving image in the second subplot and the localized points.
self.moving_axes.clear()
self.moving_axes.imshow(
self.moving_npa[self.moving_slider.value, :, :]
if self.moving_slider
else self.moving_npa,
cmap=plt.cm.Greys_r,
vmin=self.moving_min_intensity,
vmax=self.moving_max_intensity,
)
for i, pnt in enumerate(self.moving_point_indexes):
if (
self.moving_slider and int(pnt[2] + 0.5) == self.moving_slider.value
) or not self.moving_slider:
self.moving_axes.scatter(
pnt[0], pnt[1], s=90, marker="+", color=self.text_and_marker_color
)
text_in_data_coords = self.moving_axes.transData.transform(
[pnt[0], pnt[1]]
)
text_in_data_coords = self.moving_axes.transData.inverted().transform(
(
text_in_data_coords[0] + text_x_offset,
text_in_data_coords[1] + text_y_offset,
)
)
self.moving_axes.text(
text_in_data_coords[0],
text_in_data_coords[1],
str(i),
color=self.text_and_marker_color,
)
self.moving_axes.set_title(
"moving image - localized {0} points".format(len(self.moving_point_indexes))
)
self.moving_axes.set_axis_off()
# Set the zoom factor back to what it was before we cleared the axes, and rendered our data.
self.fixed_axes.set_xlim(fixed_xlim)
self.fixed_axes.set_ylim(fixed_ylim)
self.moving_axes.set_xlim(moving_xlim)
self.moving_axes.set_ylim(moving_ylim)
self.fig.canvas.draw_idle()
def clear_all(self, button):
"""
Get rid of all the data.
"""
del self.fixed_point_indexes[:]
del self.moving_point_indexes[:]
del self.click_history[:]
self.update_display()
def clear_last(self, button):
"""
Remove last point or point-pair addition (depends on whether the interface is used for localizing point pairs or
evaluation of registration).
"""
if self.click_history:
if self.known_transformation:
self.click_history.pop().pop()
self.click_history.pop().pop()
self.update_display()
def get_points(self):
"""
Get the points in the image coordinate systems.
"""
if len(self.fixed_point_indexes) != len(self.moving_point_indexes):
raise Exception(
"Number of localized points in fixed and moving images does not match."
)
fixed_point_list = [
self.fixed_image.TransformContinuousIndexToPhysicalPoint(pnt)
for pnt in self.fixed_point_indexes
]
moving_point_list = [
self.moving_image.TransformContinuousIndexToPhysicalPoint(pnt)
for pnt in self.moving_point_indexes
]
return fixed_point_list, moving_point_list
def __call__(self, event):
"""
Callback invoked when the user clicks inside the figure.
"""
# We add points only in 'edit' mode. If the spatial transformation between the two images is known, self.known_transformation was set,
# then every button_press_event will generate a point in each of the images. Finally, we enforce that all points have a corresponding
# point in the other image by not allowing the user to add multiple points in the same image, they have to add points by switching between
# the two images.
if self.viewing_checkbox.value == "edit":
if event.inaxes == self.fixed_axes:
if len(self.fixed_point_indexes) - len(self.moving_point_indexes) <= 0:
self.fixed_point_indexes.append(
(event.xdata, event.ydata, self.fixed_slider.value)
if self.fixed_slider
else (event.xdata, event.ydata)
)
self.click_history.append(self.fixed_point_indexes)
if self.known_transformation:
moving_point_physical = self.known_transformation.TransformPoint(
self.fixed_image.TransformContinuousIndexToPhysicalPoint(
self.fixed_point_indexes[-1]
)
)
moving_point_indexes = (
self.moving_image.TransformPhysicalPointToContinuousIndex(
moving_point_physical
)
)
self.moving_point_indexes.append(moving_point_indexes)
self.click_history.append(self.moving_point_indexes)
if self.moving_slider:
z_index = int(moving_point_indexes[2] + 0.5)
if (
self.moving_slider.max >= z_index
and self.moving_slider.min <= z_index
):
self.moving_slider.value = z_index
self.update_display()
if event.inaxes == self.moving_axes:
if len(self.moving_point_indexes) - len(self.fixed_point_indexes) <= 0:
self.moving_point_indexes.append(
(event.xdata, event.ydata, self.moving_slider.value)
if self.moving_slider
else (event.xdata, event.ydata)
)
self.click_history.append(self.moving_point_indexes)
if self.known_transformation:
inverse_transform = self.known_transformation.GetInverse()
fixed_point_physical = inverse_transform.TransformPoint(
self.moving_image.TransformContinuousIndexToPhysicalPoint(
self.moving_point_indexes[-1]
)
)
fixed_point_indexes = (
self.fixed_image.TransformPhysicalPointToContinuousIndex(
fixed_point_physical
)
)
self.fixed_point_indexes.append(fixed_point_indexes)
self.click_history.append(self.fixed_point_indexes)
if self.fixed_slider:
z_index = int(fixed_point_indexes[2] + 0.5)
if (
self.fixed_slider.max >= z_index
and self.fixed_slider.min <= z_index
):
self.fixed_slider.value = z_index
self.update_display()
class PointDataAquisition(object):
def __init__(self, image, window_level=None, figure_size=(10, 8)):
self.image = image
(
self.npa,
self.min_intensity,
self.max_intensity,
) = self.get_window_level_numpy_array(self.image, window_level)
self.point_indexes = []
# Create a figure.
self.fig, self.axes = plt.subplots(1, 1, figsize=figure_size)
# Connect the mouse button press to the canvas (__call__ method is the invoked callback).
self.fig.canvas.mpl_connect("button_press_event", self)
ui = self.create_ui()
# Display the data and the controls, first time we display the image is outside the "update_display" method
# as that method relies on the previous zoom factor which doesn't exist yet.
self.axes.imshow(
self.npa[self.slice_slider.value, :, :],
cmap=plt.cm.Greys_r,
vmin=self.min_intensity,
vmax=self.max_intensity,
)
self.update_display()
display(ui)
def create_ui(self):
# Create the active UI components. Height and width are specified in 'em' units. This is
# a html size specification, size relative to current font size.
self.viewing_checkbox = widgets.RadioButtons(
description="Interaction mode:", options=["edit", "view"], value="edit"
)
self.clearlast_button = widgets.Button(
description="Clear Last", width="7em", height="3em"
)
self.clearlast_button.on_click(self.clear_last)
self.clearall_button = widgets.Button(
description="Clear All", width="7em", height="3em"
)
self.clearall_button.on_click(self.clear_all)
self.slice_slider = widgets.IntSlider(
description="image z slice:",
min=0,
max=self.npa.shape[0] - 1,
step=1,
value=int((self.npa.shape[0] - 1) / 2),
width="20em",
)
self.slice_slider.observe(self.on_slice_slider_value_change, names="value")
# Layout of UI components. This is pure ugliness because we are not using a UI toolkit. Layout is done
# using the box widget and padding so that the visible UI components are spaced nicely.
bx0 = widgets.Box(padding=7, children=[self.slice_slider])
bx1 = widgets.Box(padding=7, children=[self.viewing_checkbox])
bx2 = widgets.Box(padding=15, children=[self.clearlast_button])
bx3 = widgets.Box(padding=15, children=[self.clearall_button])
return widgets.HBox(children=[widgets.HBox(children=[bx1, bx2, bx3]), bx0])
def get_window_level_numpy_array(self, image, window_level):
npa = sitk.GetArrayViewFromImage(image)
if not window_level:
return npa, npa.min(), npa.max()
else:
return (
npa,
window_level[1] - window_level[0] / 2.0,
window_level[1] + window_level[0] / 2.0,
)
def on_slice_slider_value_change(self, change):
self.update_display()
def update_display(self):
# We want to keep the zoom factor which was set prior to display, so we log it before
# clearing the axes.
xlim = self.axes.get_xlim()
ylim = self.axes.get_ylim()
# Draw the image and localized points.
self.axes.clear()
self.axes.imshow(
self.npa[self.slice_slider.value, :, :],
cmap=plt.cm.Greys_r,
vmin=self.min_intensity,
vmax=self.max_intensity,
)
# Positioning the text is a bit tricky, we position relative to the data coordinate system, but we
# want to specify the shift in pixels as we are dealing with display. We therefore (a) get the data
# point in the display coordinate system in pixel units (b) modify the point using pixel offset and
# transform back to the data coordinate system for display.
text_x_offset = -10
text_y_offset = -10
for i, pnt in enumerate(self.point_indexes):
if pnt[2] == self.slice_slider.value:
self.axes.scatter(pnt[0], pnt[1], s=90, marker="+", color="yellow")
# Get point in pixels.
text_in_data_coords = self.axes.transData.transform([pnt[0], pnt[1]])
# Offset in pixels and get in data coordinates.
text_in_data_coords = self.axes.transData.inverted().transform(
(
text_in_data_coords[0] + text_x_offset,
text_in_data_coords[1] + text_y_offset,
)
)
self.axes.text(
text_in_data_coords[0],
text_in_data_coords[1],
str(i),
color="yellow",
)
self.axes.set_title("localized {0} points".format(len(self.point_indexes)))
self.axes.set_axis_off()
# Set the zoom factor back to what it was before we cleared the axes, and rendered our data.
self.axes.set_xlim(xlim)
self.axes.set_ylim(ylim)
self.fig.canvas.draw_idle()
def add_point_indexes(self, point_index_data):
self.validate_points(point_index_data)
self.point_indexes.append(list(point_index_data))
self.update_display()
def set_point_indexes(self, point_index_data):
self.validate_points(point_index_data)
del self.point_indexes[:]
self.point_indexes = list(point_index_data)
self.update_display()
def validate_points(self, point_index_data):
for p in point_index_data:
if (
p[0] >= self.npa.shape[2]
or p[0] < 0
or p[1] >= self.npa.shape[1]
or p[1] < 0
or p[2] >= self.npa.shape[0]
or p[2] < 0
):
raise ValueError(
"Given point ("
+ ", ".join(map(str, p))
+ ") is outside the image bounds."
)
def clear_all(self, button):
del self.point_indexes[:]
self.update_display()
def clear_last(self, button):
if self.point_indexes:
self.point_indexes.pop()
self.update_display()
def get_points(self):
return [
self.image.TransformContinuousIndexToPhysicalPoint(pnt)
for pnt in self.point_indexes
]
def get_point_indexes(self):
"""
Return the point indexes, not the continous index we keep.
"""
# Round and then cast to int, just rounding will return a float
return [tuple(map(lambda x: int(round(x)), pnt)) for pnt in self.point_indexes]
def __call__(self, event):
if self.viewing_checkbox.value == "edit":
if event.inaxes == self.axes:
self.point_indexes.append(
(event.xdata, event.ydata, self.slice_slider.value)
)
self.update_display()
def multi_image_display2D(
image_list,
title_list=None,
window_level_list=None,
figure_size=(10, 8),
horizontal=True,
):
if title_list:
if len(image_list) != len(title_list):
raise ValueError("Title list and image list lengths do not match")
else:
title_list = [""] * len(image_list)
# Create a figure.
col_num, row_num = (len(image_list), 1) if horizontal else (1, len(image_list))
fig, axes = plt.subplots(row_num, col_num, figsize=figure_size)
if len(image_list) == 1:
axes = [axes]
# Get images as numpy arrays for display and the window level settings
npa_list = list(map(sitk.GetArrayViewFromImage, image_list))
if not window_level_list:
min_intensity_list = list(map(np.min, npa_list))
max_intensity_list = list(map(np.max, npa_list))
else:
min_intensity_list = list(map(lambda x: x[1] - x[0] / 2.0, window_level_list))
max_intensity_list = list(map(lambda x: x[1] + x[0] / 2.0, window_level_list))
# Draw the image(s)
for ax, npa, title, min_intensity, max_intensity in zip(
axes, npa_list, title_list, min_intensity_list, max_intensity_list
):
ax.imshow(npa, cmap=plt.cm.Greys_r, vmin=min_intensity, vmax=max_intensity)
ax.set_title(title)
ax.set_axis_off()
fig.tight_layout()
return (fig, axes)
class MultiImageDisplay(object):
"""
This class provides a GUI for displaying 3D images. It supports display of
multiple images in the same UI. The image slices are selected according to
the axis specified by the user. Each image can have a title and a slider to
scroll through the stack. The images can also share a single slider if they
have the same number of slices along the given axis. Images are either
grayscale or color. The intensity range used for display (window-level) can
be specified by the user as input to the constructor or set via the displayed
slider. For color images the intensity control slider will be disabled. This
allows us to display both color and grayscale images in the same figure with
a consistent look to the controls. The range of the intensity slider is set
to be from top/bottom 2% of intensities (accomodating for outliers). Images
are displayed either in horizontal or vertical layout, depending on the
users choice.
"""
def __init__(
self,
image_list,
axis=0,
shared_slider=False,
title_list=None,
window_level_list=None,
figure_size=(10, 8),
horizontal=True,
):
self.npa_list, wl_range, wl_init = self.get_window_level_numpy_array(
image_list, window_level_list
)
if title_list:
if len(image_list) != len(title_list):
raise ValueError("Title list and image list lengths do not match")
self.title_list = list(title_list)
else:
self.title_list = [""] * len(image_list)
# Our dynamic slice, based on the axis the user specifies
self.slc = [slice(None)] * 3
self.axis = axis
ui = self.create_ui(shared_slider, wl_range, wl_init)
display(ui)
# Create a figure.
col_num, row_num = (len(image_list), 1) if horizontal else (1, len(image_list))
self.fig, self.axes = plt.subplots(row_num, col_num, figsize=figure_size)
if len(image_list) == 1:
self.axes = [self.axes]
# Display the data and the controls, first time we display the image is outside the "update_display" method
# as that method relies on the previous zoom factor which doesn't exist yet.
for ax, npa, slider, wl_slider in zip(
self.axes, self.npa_list, self.slider_list, self.wl_list
):
self.slc[self.axis] = slice(slider.value, slider.value + 1)
# Need to use squeeze to collapse degenerate dimension (e.g. RGB image size 124 124 1 3)
ax.imshow(
np.squeeze(npa[tuple(self.slc)]),
cmap=plt.cm.Greys_r,
vmin=wl_slider.value[0],
vmax=wl_slider.value[1],
)
self.update_display()
plt.tight_layout()
def create_ui(self, shared_slider, wl_range, wl_init):
# Create the active UI components. Height and width are specified in 'em' units. This is
# a html size specification, size relative to current font size.
if shared_slider:
# Validate that all the images have the same size along the axis which we scroll through
sz = self.npa_list[0].shape[self.axis]
for npa in self.npa_list:
if npa.shape[self.axis] != sz:
raise ValueError(
"Not all images have the same size along the specified axis, cannot share slider."
)
slider = widgets.IntSlider(
description="image slice:",
min=0,
max=sz - 1,
step=1,
value=int((sz - 1) / 2),
width="20em",
)
slider.observe(self.on_slice_slider_value_change, names="value")
self.slider_list = [slider] * len(self.npa_list)
slicer_box = widgets.Box(padding=7, children=[slider])
else:
self.slider_list = []
for npa in self.npa_list:
slider = widgets.IntSlider(
description="image slice:",
min=0,
max=npa.shape[self.axis] - 1,
step=1,
value=int((npa.shape[self.axis] - 1) / 2),
width="20em",
)
slider.observe(self.on_slice_slider_value_change, names="value")
self.slider_list.append(slider)
slicer_box = widgets.Box(padding=7, children=self.slider_list)
self.wl_list = []
# Each image has a window-level slider, but it is disabled if the image
# is a color image len(npa.shape)==4 . This allows us to display both
# color and grayscale images in the same UI while retaining a reasonable
# layout for the sliders.
for r_values, i_values, npa in zip(wl_range, wl_init, self.npa_list):
wl_range_slider = widgets.IntRangeSlider(
description="intensity:",
min=r_values[0],
max=r_values[1],
step=1,
value=[i_values[0], i_values[1]],
width="20em",
disabled=len(npa.shape) == 4,
)
wl_range_slider.observe(self.on_wl_slider_value_change, names="value")
self.wl_list.append(wl_range_slider)
wl_box = widgets.Box(padding=7, children=self.wl_list)
return widgets.VBox(children=[slicer_box, wl_box])
def get_window_level_numpy_array(self, image_list, window_level_list):
# Using GetArray and not GetArrayView because we don't keep references
# to the original images. If they are deleted outside the view would become
# invalid, so we use a copy wich guarentees that the gui is consistent.
npa_list = list(map(sitk.GetArrayFromImage, image_list))
wl_range = []
wl_init = []
# We need to iterate over the images because they can be a mix of
# grayscale and color images. If they are color we set the wl_range
# to [0,255] and the wl_init is equal, ignoring the window_level_list
# entry.
for i, npa in enumerate(npa_list):
if len(npa.shape) == 4: # color image
wl_range.append((0, 255))
wl_init.append((0, 255))
# ignore any window_level_list entry
else:
# We don't take the minimum/maximum values, just in case there are outliers (top/bottom 2%)
min_max = np.percentile(npa.flatten(), [2, 98])
wl_range.append((min_max[0], min_max[1]))
if not window_level_list:
wl_init.append(wl_range[-1])
else:
wl = window_level_list[i]
if wl:
wl_init.append((wl[1] - wl[0] / 2.0, wl[1] + wl[0] / 2.0))
else:
wl_init.append(wl_range[-1])
return (npa_list, wl_range, wl_init)
def on_slice_slider_value_change(self, change):
self.update_display()
def on_wl_slider_value_change(self, change):
self.update_display()
def update_display(self):
# Draw the image(s)
for ax, npa, title, slider, wl_slider in zip(
self.axes, self.npa_list, self.title_list, self.slider_list, self.wl_list
):
# We want to keep the zoom factor which was set prior to display, so we log it before
# clearing the axes.
xlim = ax.get_xlim()
ylim = ax.get_ylim()
self.slc[self.axis] = slice(slider.value, slider.value + 1)
ax.clear()
# Need to use squeeze to collapse degenerate dimension (e.g. RGB image size 124 124 1 3)
ax.imshow(
np.squeeze(npa[tuple(self.slc)]),
cmap=plt.cm.Greys_r,
vmin=wl_slider.value[0],
vmax=wl_slider.value[1],
)
ax.set_title(title)
ax.set_axis_off()
# Set the zoom factor back to what it was before we cleared the axes, and rendered our data.
ax.set_xlim(xlim)
ax.set_ylim(ylim)
self.fig.canvas.draw_idle()
class ROIDataAquisition(object):
"""
This class provides a GUI for selecting box shaped Regions Of Interest (ROIs). Each ROI is represented as a
tuple: ((min_x,max_x),(min_y,max_y), and possibly (min_z,max_z)) if dealing with a 3D image.
When using the zoom/pan tool from the toolbar ROI selection is disabled. Once you click again on the zoom/pan
button zooming/panning will be disabled and ROI selection is enabled.
Note that when you are marking the ROI on a slice that is outside the Z-range selected by the
range slider, once you are done selecting the ROI, you will see no change on the current slice. This is the
correct behavior, though initially you may be surprised by it.
"""
def __init__(self, image, window_level=None, figure_size=(10, 8)):
self.image = image
(
self.npa,
self.min_intensity,
self.max_intensity,
) = self.get_window_level_numpy_array(self.image, window_level)
self.rois = []
# ROI display settings
self.roi_display_properties = dict(
facecolor="red", edgecolor="black", alpha=0.2, fill=True
)
ui = self.create_ui()
display(ui)
# Create a figure.
self.fig, self.axes = plt.subplots(1, 1, figsize=figure_size)
# Connect the mouse button press to the canvas (__call__ method is the invoked callback).
self.fig.canvas.mpl_connect("button_press_event", self)
self.roi_selector = RectangleSelector(
self.axes,
lambda eclick, erelease: None,
drawtype="box",
useblit=True,
button=[1, 3], # Left, right buttons only.
minspanx=5,
minspany=5, # Ignore motion smaller than 5 pixels.
spancoords="pixels",
interactive=True,
rectprops=self.roi_display_properties,
)
self.roi_selector.set_visible(False)
# Display the data and the controls, first time we display the image is outside the "update_display" method
# as that method relies on the existance of a previous image which is removed from the figure.
self.axes.imshow(
self.npa[self.slice_slider.value, :, :] if self.slice_slider else self.npa,
cmap=plt.cm.Greys_r,
vmin=self.min_intensity,
vmax=self.max_intensity,
)
self.update_display()
def create_ui(self):
# Create the active UI components. Height and width are specified in 'em' units. This is
# a html size specification, size relative to current font size.
self.addroi_button = widgets.Button(
description="Add ROI", width="7em", height="3em"
)
self.addroi_button.on_click(self.add_roi)
self.clearlast_button = widgets.Button(
description="Clear Last", width="7em", height="3em"
)
self.clearlast_button.on_click(self.clear_last)
self.clearall_button = widgets.Button(
description="Clear All", width="7em", height="3em"
)
self.clearall_button.on_click(self.clear_all)
# Create sliders only if 3D image
self.slice_slider = self.roi_range_slider = None
if self.npa.ndim == 3:
self.roi_range_slider = widgets.IntRangeSlider(
description="ROI z range:",
min=0,
max=self.npa.shape[0] - 1,
step=1,
value=[0, self.npa.shape[0] - 1],
width="20em",
)
bx4 = widgets.Box(padding=15, children=[self.roi_range_slider])
self.slice_slider = widgets.IntSlider(
description="image z slice:",
min=0,
max=self.npa.shape[0] - 1,
step=1,
value=int((self.npa.shape[0] - 1) / 2),
width="20em",
)
self.slice_slider.observe(self.on_slice_slider_value_change, names="value")
bx0 = widgets.Box(padding=7, children=[self.slice_slider])
# Layout of UI components. This is pure ugliness because we are not using a UI toolkit. Layout is done
# using the box widget and padding so that the visible UI components are spaced nicely.
bx1 = widgets.Box(padding=7, children=[self.addroi_button])
bx2 = widgets.Box(padding=15, children=[self.clearlast_button])
bx3 = widgets.Box(padding=15, children=[self.clearall_button])
return (
widgets.HBox(
children=[
widgets.HBox(children=[bx1, bx2, bx3]),
widgets.VBox(children=[bx0, bx4]),
]
)
if self.npa.ndim == 3
else widgets.HBox(children=[widgets.HBox(children=[bx1, bx2, bx3])])
)
def on_slice_slider_value_change(self, change):
self.update_display()
def get_window_level_numpy_array(self, image, window_level):
npa = sitk.GetArrayViewFromImage(image)
# We don't take the minimum/maximum values, just in case there are outliers (top/bottom 2%)
if not window_level:
min_max = np.percentile(npa.flatten(), [2, 98])
return npa, min_max[0], min_max[1]
else:
return (
npa,
window_level[1] - window_level[0] / 2.0,
window_level[1] + window_level[0] / 2.0,
)
def update_display(self):
# Draw the image and ROIs.
# imshow adds an image to the axes, so we also remove the previous one.
self.axes.imshow(
self.npa[self.slice_slider.value, :, :] if self.slice_slider else self.npa,
cmap=plt.cm.Greys_r,
vmin=self.min_intensity,
vmax=self.max_intensity,
)
self.axes.images[0].remove()
# Iterate over all of the ROIs and only display/undisplay those that are relevant.
if self.slice_slider:
for roi_data in self.rois:
if (
self.slice_slider.value >= roi_data[3][0]
and self.slice_slider.value <= roi_data[3][1]
):
roi_data[0].set_visible(True)
else:
roi_data[0].set_visible(False)
self.axes.set_title("selected {0} ROIs".format(len(self.rois)))
self.axes.set_axis_off()
self.fig.canvas.draw_idle()
def add_roi_data(self, roi_data):
"""
Add regions of interest to this GUI.
Input is an iterable containing tuples where each tuple contains
either two or three tuples (min_x,max_x),(min_y,max_y), (min_z,max_z).
depending on the image dimensionality. The ROI
is the box defined by these integer values and includes
both min/max values.
"""
self.validate_rois(roi_data)
for roi in roi_data:
self.rois.append(
(
patches.Rectangle(
(roi[0][0], roi[1][0]),
roi[0][1] - roi[0][0],
roi[1][1] - roi[1][0],
**self.roi_display_properties
),
roi[0],
roi[1],
roi[2] if self.npa.ndim == 3 else None,
)
)
self.axes.add_patch(self.rois[-1][0])
self.update_display()
def set_rois(self, roi_data):
"""
Clear any existing ROIs and set the display to the given ones.
Input is an iterable containing tuples where each tuple contains
two or three tuples (min_x,max_x),(min_y,max_y), (min_z,max_z) depending
on the image dimensionality. The ROI
is the box defined by these integer values and includes
both min/max values.
"""
self.clear_all_data()
self.add_roi_data(roi_data)
def validate_rois(self, roi_data):
for roi in roi_data:
for i, bounds in enumerate(roi, 1):
if bounds[0] > bounds[1]:
raise ValueError(
"First element in each tuple is expected to be smaller than second element, error in ROI ("
+ ", ".join(map(str, roi))
+ ")."
)
# Note that SimpleITK uses x-y-z specification vs. numpy's z-y-x
if not (
bounds[0] >= 0 and bounds[1] < self.npa.shape[self.npa.ndim - i]
):
raise ValueError(
"Given ROI ("
+ ", ".join(map(str, roi))
+ ") is outside the image bounds."
)
def add_roi(self, button):
if self.roi_selector.visible:
self.roi_selector.set_visible(False)
# Extent is in sub-pixel coordinates, we need it in pixels/voxels.
roi_extent = [int(round(coord)) for coord in self.roi_selector.extents]
# We keep the patch for display and the x,y,z ranges of the ROI.
self.rois.append(
(
patches.Rectangle(
(roi_extent[0], roi_extent[2]),
roi_extent[1] - roi_extent[0],
roi_extent[3] - roi_extent[2],
**self.roi_display_properties
),
(roi_extent[0], roi_extent[1]),
(roi_extent[2], roi_extent[3]),