-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathVolumeAnnotator.py
More file actions
1511 lines (1220 loc) · 57 KB
/
VolumeAnnotator.py
File metadata and controls
1511 lines (1220 loc) · 57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
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
#!/usr/bin/env python
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
import numpy as np
import imageio
import sys
import os
from matplotlib.widgets import Slider, Button, RadioButtons, TextBox
from matplotlib.backend_bases import MouseButton
import time
import argparse
from gc_segment.utils import *
IMAGE_RECTANGLE = [0.03, 0.10, 0.60, 0.70]
KEYPRESS_MOVE_STEP = 5
FOREGROUND = 'Object'
BACKGROUND = 'Background'
ERASE = 'Erase'
CLICK = 'Click'
ANNOTATION = 'Annotation'
SEGMENTATION = 'Segmentation'
TICK_STEP = 20
# Axes.
X, Y, Z = 'X', 'Y', 'Z'
ANNO_CHOICES = [FOREGROUND, BACKGROUND, ERASE, CLICK]
ANNO_KEYPRESS_DICT = {
'q': [FOREGROUND, 0],
'w': [BACKGROUND, 1],
'e': [ERASE, 2],
'r': [CLICK, 3],
}
ANNO_SEG_KEYPRESS_DICT = {
'a' : [ANNOTATION, 0],
's' : [SEGMENTATION, 1],
}
ANNO_SEG_CHOICES = [ANNOTATION, SEGMENTATION]
AXIS_CHOICES = [X, Y, Z]
AXIS_KEYPRESS_DICT = {
'3': [Z, 2],
'2': [Y, 1],
'1': [X, 0],
}
PLANES_KEYPRESS_DICT = {
'z': 1,
'm': -1,
}
MOVE_KEYPRESS_DICT = {
'up': [ 0, -KEYPRESS_MOVE_STEP],
'down': [ 0, KEYPRESS_MOVE_STEP],
'left': [-KEYPRESS_MOVE_STEP, 0],
'right': [ KEYPRESS_MOVE_STEP, 0],
}
RECOGNISED_KEYBOARD_SHORTCUTS = list(ANNO_KEYPRESS_DICT.keys()) + \
list(PLANES_KEYPRESS_DICT.keys()) + \
list(AXIS_KEYPRESS_DICT) + \
list(MOVE_KEYPRESS_DICT) + \
list(ANNO_SEG_KEYPRESS_DICT) # + <other keyboard shorcuts>
FOREGROUND_NAMES = [FOREGROUND, 'Foreground']
ANNO_DIR = 'annotation/'
MASK_DIR = 'mask/mask0/'
OUTPUT_DIR = 'segmentation_cropped/'
BLK = {
FOREGROUND: 1,
BACKGROUND: 10,
}
BOX_COORDS = {
'/media/scratch/mihir/20190613/': [1886, 1168, 458, 392],
'./data/20190613/': [1886, 1168, 458, 392],
'../data/20190613/': [1886, 1168, 458, 392],
'./data/20190613_full/': [1886, 1168, 458, 392],
'./data/20190821/': [3768, 1829, 448, 294],
'../data/20190821/': [3768, 1829, 448, 294],
'../data/20190919/': [2160, 1018, 728, 252],
}
def bound_low(value, bound):
"""
Lower-bound a value according to given bound.
"""
return max([value, bound])
def bound_high(value, bound):
"""
Upper-bound a value according to a given bound.
"""
return min([value, bound])
def slice_file_name(z_, label_):
"""
Define a file name for slice number z_ for the foreground and background.
"""
assert label_ in [FOREGROUND, BACKGROUND], 'slice_file_name: Supplied label must be \
either {} or {}.'.format(FOREGROUND, BACKGROUND)
return '%s_%d.tif' % (label_, z_)
def info_from_filename(filename):
"""
Get information (z, label) from the filename.
"""
z = int(os.path.split(filename)[-1].split('.')[0].split('_')[1])
if any([f in filename for f in FOREGROUND_NAMES]):
label = FOREGROUND
else:
label = BACKGROUND
return z, label
class VolumeAnnotator(object):
def __init__(
self,
cfg,
**kwargs,
):
"""
Init function for ForegroundBackground annotator.
Inputs
------
data_path Path to directory containing TIFF stack.
anno_dir Directory in which to save annotations.
Default: 'annotation/'
"""
options = load_yaml(cfg)
# Get experiment name
self.experiment_name = '.'.join(os.path.split(cfg)[-1].split('.')[:-1])
self.output_dir = os.path.join('output/', self.experiment_name)
if not os.path.exists(self.output_dir):
os.makedirs(self.output_dir)
self.data_path = os.path.expanduser(options.data_path)
assert os.path.exists(
self.data_path), 'Specified directory {} does not exist!'.format(self.data_path)
anno_dir = os.path.join(self.output_dir, 'annotation/')
data_dir = os.path.join(self.output_dir, 'data/')
mask_dir = os.path.join(self.output_dir, MASK_DIR)
self.anno_dir = anno_dir
self.data_dir = data_dir
self.mask_dir = mask_dir
# Make directories if they do not exist.
for dir_ in [self.anno_dir, self.data_dir, self.mask_dir]:
if not os.path.exists(dir_):
os.makedirs(dir_)
# while os.path.exists(anno_dir):
# response = 'p'
# while response not in ['', 'y', 'Y', 'n', 'N']:
# response = input('{} already exists. Annotations in this directory \
# will be overwritten. Continue (Y/n)? '.format(anno_dir))
#
# _ = os.popen('rm -rf {}'.format(anno_dir)).read()
#
# self.anno_dir = anno_dir
# os.makedirs(anno_dir)
# Default kwargs.
default_kwargs_ = {
# Size of the figure
'figure_size_': [18, 10],
# Colour map to display image.
'im_cmap_': 'hsv',
# Colour of the sliders and boxes.
'face_colour_': [0.85, 0.85, 0.85],
'ax_colour_': 'lightgoldenrodyellow',
'hover_colour_': '0.8',
# Margin left.
'm_left_': 0.05,
# Margin right.
'm_right_': 0.95,
# Margin top.
'm_top_': 0.95,
# Margin bottom.
'm_bottom_': 0.05,
}
# Set kwargs.
for k in default_kwargs_:
if hasattr(kwargs, k):
setattr(self, k, kwargs[k])
else:
setattr(self, k, default_kwargs_[k])
# Check that the data path and image exist.
assert os.path.exists(self.data_path), \
'Given data path {} does not exist!'.format(self.data_path)
# Get box coordinates.
if options.coords:
self.X, self.Y, self.W, self.H = options.coords
else:
# BOX_COORDS[self.data_path]
self.X, self.Y, self.W, self.H = None, None, None, None
# Get image names.
self.image_names = sorted(os.listdir(self.data_path))
# Z slicing
if not options.z_limits:
self.z_limits = [0, len(self.image_names)]
else:
self.z_limits = options.z_limits
# Number of slices
self.n_slices = self.z_limits[1] - self.z_limits[0]
# Read TIFF stack.
self.stack = []
for _z in range(self.z_limits[0], self.z_limits[1]):
_f = self.image_names[_z]
_img_path = os.path.join(self.data_path, _f)
# Read slice.
_slice = imageio.imread(_img_path)
# Crop the slice if limits are specified.
if self.X is not None:
_slice = _slice[self.Y: self.Y + self.H,
self.X: self.X + self.W]
# Save into data dir
imageio.imsave(os.path.join(self.data_dir, _f), _slice)
# Push into stack
self.stack.append(_slice)
# Concatenate into one volume.
self.stack = np.stack(self.stack)
# Image sizes.
self.stack_depth = self.stack.shape[0]
self.stack_height = self.stack.shape[1]
self.stack_width = self.stack.shape[2]
# Initialise empty annotation volumes.
self.fg_annotation_ = np.zeros(self.stack.shape).astype(np.uint8)
self.bg_annotation_ = np.zeros(self.stack.shape).astype(np.uint8)
# Copy the stack into another image---this is the image that is displayed.
self.disp_stack_ = self.stack.copy()
self.disp_stack_ = np.stack(
(self.disp_stack_, self.disp_stack_, self.disp_stack_)).transpose([1, 2, 3, 0])
# Initialise the viewing rectangle. This is a new addition (2020-10-19)
# to help focus on smaller regions during annotation of big volumes.
#
# In essence, this restricts the viewing rectangle to a maximum
# size determined by self.max_area_display_size
self.max_area_display_size = options.max_area_display_size
self.x_view_size = min(self.max_area_display_size, self.W)
self.y_view_size = min(self.max_area_display_size, self.H)
self.z_view_size = min(self.max_area_display_size, self.n_slices)
# Keep one tuple for each viewing axis. This tuple defines the top-left
# corner of the viewing volume depending on the axis. The depth of
# this volume is all planes.
self.viewing_rect = {}
for axis_ in AXIS_CHOICES:
self.viewing_rect[axis_] = [0, 0]
# When we use the move function to move around in the volume, these
# values will be changed.
# Define viewing rectangle sizes depending on the viewing axis.
self.view_sizes = {}
self.view_sizes[X] = [self.y_view_size, self.z_view_size]
self.view_sizes[Y] = [self.x_view_size, self.z_view_size]
self.view_sizes[Z] = [self.x_view_size, self.y_view_size]
# Define stack sizes according to viewing axis.
self.stack_sizes = {}
self.stack_sizes[X] = [self.stack_height, self.stack_depth]
self.stack_sizes[Y] = [self.stack_width, self.stack_depth]
self.stack_sizes[Z] = [self.stack_width, self.stack_height]
# Dictionary to determine which annotation volume to contribute to.
self.annotation_volume_dict = {
FOREGROUND: self.fg_annotation_,
BACKGROUND: self.bg_annotation_,
}
# Which channels to modify in disp_stack_ for FG and BG.
self.fg_channel = 2 # Blue
self.bg_channel = 0 # Red
# View axis is Z by default.
self.view_axis_ = Z
# Currently shown slice on the figure. Initialise this to zero for all axes.
self.x_ = 0
self.y_ = 0
self.z_ = 0
# Currently chosen annotation mode. It is foreground by default.
self.ann_mode_ = FOREGROUND
# Create a dictionary to remember brush sizes. This allows for easy switching
# switching between annotation modes, as brush sizes are remembered.
# Typically, objects use a smaller brush size.
self.brush_sizes_ = {}
for ann_mode_ in ANNO_CHOICES:
self.brush_sizes_[ann_mode_] = 1
# Currently chosen brush size. Initially is 1.
self.brush_size_ = 1
# Whether mouse is currently pressed.
self.mouse_primary_pressed_ = False
self.mouse_secondary_pressed_ = False
# Set self.initialised_ to False, meaning the figure has not been initialised yet.
self.initialised_ = False
# Array determining whether there are annotations for a certain plane.
self.annotated_planes_ = np.zeros(self.n_slices, dtype=bool)
# Array to read the previous segementation. This is to visualise the annotation and
# segmentation together side-by-side.
self.prev_segmentation_ = np.zeros_like(self.disp_stack_)
self.prev_segmentation_[:,:,:,:] = self.disp_stack_[:,:,:,:]
# Default display mode is ANNOTATION
self.display_mode_ = ANNOTATION
# If self.anno_dir already exists, it contains a previously saved annotation.
# Load it.
if os.path.exists(self.anno_dir):
# Path to load from is in text.
saved_files = os.listdir(self.anno_dir)
# Load all files. The filename determines which annotation slice to set.
for sf in saved_files:
sf_path = os.path.join(self.anno_dir, sf)
anno = imageio.imread(sf_path) / 255
z, label = info_from_filename(sf_path)
annotated_flag_ = anno.sum() > 0
if label in FOREGROUND_NAMES:
self.fg_annotation_[z, :, :] = anno
ds_ = (1 - anno) * \
self.disp_stack_[z, :, :, self.fg_channel]
fg_ = anno * 255
self.disp_stack_[z, :, :, self.fg_channel] = ds_ + fg_
else:
self.bg_annotation_[z, :, :] = anno
ds_ = (1 - anno) * \
self.disp_stack_[z, :, :, self.bg_channel]
bg_ = anno * 255
self.disp_stack_[z, :, :, self.bg_channel] = ds_ + bg_
# Mark this plane as annotated.
self.annotated_planes_[z] = annotated_flag_
else:
os.makedirs(self.anno_dir)
# Load previous segmentation, if it exists.
if os.path.exists(self.mask_dir):
# Load previously discovered segmentation.
prev_seg_files = sorted(os.listdir(self.mask_dir))
# Load each image
for z, sf in enumerate(prev_seg_files):
sf_path = os.path.join(self.mask_dir, sf)
seg = imageio.imread(sf_path) / 255
ds_ = (1 - seg) * \
self.stack[z, :, :]
fg_ = seg * 255
self.prev_segmentation_[z,:,:,0] = ds_ + fg_
self.prev_segmentation_[z,:,:,1] = ds_ + fg_
# Update current figure.
def _update_figure(self, axis_switch=False):
"""
Redraws the figure for the current value of z_.
axis_switch: whether viewing axis has been switched to make this call.
"""
if self.view_axis_ == X:
# Determine the viewing rectangle.
y_min, z_min = self.viewing_rect[self.view_axis_]
y_max = y_min + self.y_view_size
z_max = z_min + self.z_view_size
if self.display_mode_ == ANNOTATION:
display_stack_ = self.disp_stack_[z_min:z_max, y_min:y_max, self.x_, :]
elif self.display_mode_ == SEGMENTATION:
display_stack_ = self.prev_segmentation_[z_min:z_max, y_min:y_max, self.x_,:]
elif self.view_axis_ == Y:
# Determine the viewing rectangle.
x_min, z_min = self.viewing_rect[self.view_axis_]
x_max = x_min + self.x_view_size
z_max = z_min + self.z_view_size
if self.display_mode_ == ANNOTATION:
display_stack_ = self.disp_stack_[z_min:z_max, self.y_, x_min:x_max, :]
elif self.display_mode_ == SEGMENTATION:
display_stack_ = self.prev_segmentation_[z_min:z_max, self.y_, x_min:x_max, :]
elif self.view_axis_ == Z:
# Determine the viewing rectangle.
x_min, y_min = self.viewing_rect[self.view_axis_]
x_max = x_min + self.x_view_size
y_max = y_min + self.y_view_size
if self.display_mode_ == ANNOTATION:
display_stack_ = self.disp_stack_[self.z_, y_min:y_max, x_min:x_max, :]
elif self.display_mode_ == SEGMENTATION:
display_stack_ = self.prev_segmentation_[self.z_, y_min:y_max, x_min:x_max, :]
if axis_switch:
if self.ax_image_ is None:
self.ax_image_ = plt.axes(IMAGE_RECTANGLE) # Was 0.05, 0.15, 0.55, 0.8
else:
self.ax_image_ = plt.axes(self.ax_image_)
self.ax_image_.margins(x=0, y=0, tight=True)
self.image_handle_ = self.ax_image_.imshow(display_stack_,
cmap=self.im_cmap_,
aspect='equal',)
else:
self.image_handle_.set_data(display_stack_)
self._set_axis_ticks()
self._set_axis_labels()
self.figure_.canvas.draw_idle()
return
def _update_annotation_visual(self):
"""
Updates annotation in self.disp_stack_ for current z.
"""
self.disp_stack_[self.z_, :, :,
self.fg_channel][self.fg_annotation_[self.z_] > 0] = 255
self.disp_stack_[self.z_, :, :,
self.bg_channel][self.bg_annotation_[self.z_] > 0] = 255
return
# Handle mouse press.
def _handle_mouse_press(self,
event):
"""
Function to handle mouse press for annotation.
Mouse press is registered for annotation only if it was pressed
while over the plot showing the image.
"""
# First, make sure the figure has been initialised.
assert self.initialised_, 'Figure has not been initialised yet!'
# Check whether event occurs over ax_image_
if event.inaxes == self.ax_image_:
# Check if the primary or secondary button is pressed.
if event.button == MouseButton.LEFT:
# This button press shall be used for annotation.
self.mouse_primary_pressed_ = True
self.annotate_patch(event.xdata, event.ydata)
# Check if secondary was pressed instead.
elif event.button == MouseButton.RIGHT:
self.mouse_secondary_pressed_ = True
# Save the location where this button was pressed.
# This will be used to determine how to move
# the image.
self.move_image_location_ = [int(np.floor(event.xdata)),
int(np.floor(event.ydata))]
# Save the viewing rectangle at this point.
self.move_viewing_rect_ = self.viewing_rect[self.view_axis_]
return
def _handle_mouse_move(self,
event):
"""
Handle how annotations occur when mouse is moved.
Annotations are recorded only if the button is pressed while the mouse is moving.
"""
# First, make sure the figure has been initialised.
assert self.initialised_, 'Figure has not been initialised yet!'
if (not self.mouse_primary_pressed_ and not self.mouse_secondary_pressed_) \
or event.inaxes != self.ax_image_:
return
# If the primary button is pressed, annotate.
if self.mouse_primary_pressed_:
# Do nothing if ann_mode_ is CLICK.
if self.ann_mode_ == CLICK:
return
self.annotate_patch(event.xdata, event.ydata)
# If the secondary button is pressed, move
elif self.mouse_secondary_pressed_:
# Call the move function
self.move_image(location=[event.xdata, event.ydata], displacement=None)
return
def _handle_mouse_release(self,
event):
"""
Handle mouse release.
"""
# First, make sure the figure has been initialised.
assert self.initialised_, 'Figure has not been initialised yet!'
# Check which mouse button was pressed.
if self.mouse_primary_pressed_:
# The button had been pressed to annotate.
self.mouse_primary_pressed_ = False
# Mark this plane as annotated if it still contains any annotations.
if self.fg_annotation_[self.z_].sum() > 0 or self.bg_annotation_[self.z_].sum() > 0:
self.annotated_planes_[self.z_] = True
else:
self.annotated_planes_[self.z_] = False
elif self.mouse_secondary_pressed_:
self.mouse_secondary_pressed_ = False
# Just call _update_figure() one last time.
self._update_figure()
return
def annotate_patch(self, xloc, yloc):
"""
Annotate patch centered at (xloc, yloc).
Uses current state to determine what kind of annotation will be done.
"""
# If we are not in annotation display mode, skip.
if self.display_mode_ != ANNOTATION:
return
# TODO: The annotation is dependent on the viewing rectangle.
# Find where the event occurred.
loc_x_, loc_y_ = xloc, yloc
loc_x_ = int(np.floor(loc_x_))
loc_y_ = int(np.floor(loc_y_))
# Get the viewing window.
ref_win_x, ref_win_y = self.viewing_rect[self.view_axis_]
# Find coordinates of box to annotate.
bs2_ = (self.brush_size_ + 1) // 2
col_s_ = max([ref_win_x + loc_x_ - bs2_ + 1, 0])
col_e_ = min([ref_win_x + loc_x_ + bs2_, self.stack_width])
row_s_ = max([ref_win_y + loc_y_ - bs2_ + 1, 0])
row_e_ = min([ref_win_y + loc_y_ + bs2_, self.stack_height])
# Record annotation. This is dependent on what is the current viewing axis.
# If viewing axis is X, we annotate in the Y-Z plane.
if self.view_axis_ == X:
if self.ann_mode_ == FOREGROUND:
self.fg_annotation_[row_s_:row_e_, col_s_:col_e_, self.x_] = 1
self.bg_annotation_[row_s_:row_e_, col_s_:col_e_, self.x_] = 0
self.disp_stack_[row_s_:row_e_, col_s_:col_e_,
self.x_, self.fg_channel] = 255
self.disp_stack_[row_s_:row_e_, col_s_:col_e_,
self.x_, self.bg_channel] = \
self.stack[row_s_:row_e_, col_s_:col_e_, self.x_]
elif self.ann_mode_ == BACKGROUND:
self.bg_annotation_[row_s_:row_e_, col_s_:col_e_, self.x_] = 1
self.fg_annotation_[row_s_:row_e_, col_s_:col_e_, self.x_] = 0
self.disp_stack_[row_s_:row_e_, col_s_:col_e_,
self.x_, self.bg_channel] = 255
self.disp_stack_[row_s_:row_e_, col_s_:col_e_,
self.x_, self.fg_channel] = \
self.stack[row_s_:row_e_, col_s_:col_e_, self.x_]
elif self.ann_mode_ == ERASE:
self.bg_annotation_[row_s_:row_e_, col_s_:col_e_, self.x_] = 0
self.fg_annotation_[row_s_:row_e_, col_s_:col_e_, self.x_] = 0
self.disp_stack_[row_s_:row_e_, col_s_:col_e_,
self.x_, self.bg_channel] = \
self.stack[row_s_:row_e_, col_s_:col_e_, self.x_]
self.disp_stack_[row_s_:row_e_, col_s_:col_e_,
self.x_, self.fg_channel] = \
self.stack[row_s_:row_e_, col_s_:col_e_, self.x_]
# If viewing axis is Y, we annotate in the X-Z plane.
elif self.view_axis_ == Y:
if self.ann_mode_ == FOREGROUND:
self.fg_annotation_[row_s_:row_e_, self.y_, col_s_:col_e_] = 1
self.bg_annotation_[row_s_:row_e_, self.y_, col_s_:col_e_] = 0
self.disp_stack_[row_s_:row_e_, self.y_,
col_s_:col_e_, self.fg_channel] = 255
self.disp_stack_[row_s_:row_e_, self.y_,
col_s_:col_e_, self.bg_channel] = \
self.stack[row_s_:row_e_, self.y_, col_s_:col_e_]
elif self.ann_mode_ == BACKGROUND:
self.bg_annotation_[row_s_:row_e_, self.y_, col_s_:col_e_] = 1
self.fg_annotation_[row_s_:row_e_, self.y_, col_s_:col_e_] = 0
self.disp_stack_[row_s_:row_e_, self.y_,
col_s_:col_e_, self.bg_channel] = 255
self.disp_stack_[row_s_:row_e_, self.y_, col_s_:col_e_, self.fg_channel] = \
self.stack[row_s_:row_e_, self.y_, col_s_:col_e_]
elif self.ann_mode_ == ERASE:
self.bg_annotation_[row_s_:row_e_, self.y_, col_s_:col_e_] = 0
self.fg_annotation_[row_s_:row_e_, self.y_, col_s_:col_e_] = 0
self.disp_stack_[row_s_:row_e_, self.y_, col_s_:col_e_, self.bg_channel] = \
self.stack[row_s_:row_e_, self.y_, col_s_:col_e_]
self.disp_stack_[row_s_:row_e_, self.y_, col_s_:col_e_, self.fg_channel] = \
self.stack[row_s_:row_e_, self.y_, col_s_:col_e_]
# If viewing axis is Z, we annotate in the X-Y plane.
elif self.view_axis_ == Z:
if self.ann_mode_ == FOREGROUND:
self.fg_annotation_[self.z_, row_s_:row_e_, col_s_:col_e_] = 1
self.bg_annotation_[self.z_, row_s_:row_e_, col_s_:col_e_] = 0
self.disp_stack_[self.z_, row_s_:row_e_,
col_s_:col_e_, self.fg_channel] = 255
self.disp_stack_[self.z_, row_s_:row_e_, col_s_:col_e_, self.bg_channel] = \
self.stack[self.z_, row_s_:row_e_, col_s_:col_e_]
elif self.ann_mode_ == BACKGROUND:
self.bg_annotation_[self.z_, row_s_:row_e_, col_s_:col_e_] = 1
self.fg_annotation_[self.z_, row_s_:row_e_, col_s_:col_e_] = 0
self.disp_stack_[self.z_, row_s_:row_e_,
col_s_:col_e_, self.bg_channel] = 255
self.disp_stack_[self.z_, row_s_:row_e_, col_s_:col_e_, self.fg_channel] = \
self.stack[self.z_, row_s_:row_e_, col_s_:col_e_]
elif self.ann_mode_ == ERASE:
self.bg_annotation_[self.z_, row_s_:row_e_, col_s_:col_e_] = 0
self.fg_annotation_[self.z_, row_s_:row_e_, col_s_:col_e_] = 0
self.disp_stack_[self.z_, row_s_:row_e_, col_s_:col_e_, self.bg_channel] = \
self.stack[self.z_, row_s_:row_e_, col_s_:col_e_]
self.disp_stack_[self.z_, row_s_:row_e_, col_s_:col_e_, self.fg_channel] = \
self.stack[self.z_, row_s_:row_e_, col_s_:col_e_]
# Update display.
self._update_figure()
def move_image(self,
location=None, displacement=None):
"""
Move the viewing area depending on xloc and yloc.
location is used when moving with the mouse. It should be a list/tuple
[xloc, yloc].
displacement is used when moving with the arrow keys.
It should be a tuple [xdisp, ydisp]
"""
# First, make sure the figure has been initialised.
assert self.initialised_, 'Figure has not been initialised yet!'
if location is not None:
xloc, yloc = location
# Convert xloc and yloc to integers
xloc = int(np.floor(xloc))
yloc = int(np.floor(yloc))
# Get the original click location for the move.
ref_move_x, ref_move_y = self.move_image_location_
# The amount to move along X or Y is now dependent on where the current
# location of the mouse is relative to this.
# After the image has been moved, the original location must
# occur at the current location. That is to say, the mouse
# should "stick to" the original location.
#
# To achieve this, we must move the coordinates of the viewing
# rectangle.
# Get the current viewing rectangle.
view_rect_x, view_rect_y = self.move_viewing_rect_
# Get the difference between xloc and ref_move_x, and similarly for y.
move_x = ref_move_x - xloc
move_y = ref_move_y - yloc
# Store xloc, yloc as the new move_location_
self.move_location_ = [xloc, yloc]
elif displacement is not None:
view_rect_x, view_rect_y = self.viewing_rect[self.view_axis_]
move_x, move_y = displacement
move_x = int(np.floor(move_x))
move_y = int(np.floor(move_y))
else:
raise ValueError('One of location and displacement must be specified when calling move_image!')
# The new location is the old location plus this difference
new_loc_x = view_rect_x + move_x
new_loc_y = view_rect_y + move_y
# New locations are view_rect_x + move_x and view_rect_y + move_y.
# But these must be kept within bounds [0, self.self.<axis>_view_size]
# Lower bound it first.
new_loc_x = bound_low(new_loc_x, 0)
new_loc_y = bound_low(new_loc_y, 0)
# Upper bound it now, depending on the axis.
x_view_size, y_view_size = self.view_sizes[self.view_axis_]
x_size, y_size = self.stack_sizes[self.view_axis_]
new_loc_x = bound_high(new_loc_x, x_size - x_view_size)
new_loc_y = bound_high(new_loc_y, y_size - y_view_size)
# Store the new location
self.viewing_rect[self.view_axis_] = [new_loc_x, new_loc_y]
# Update the figure
self._update_figure()
return
def _handle_display_mode_radio(self,
label):
"""
Handle choice of display mode---annotation or segmentation
"""
# First, make sure the figure has been initialised.
assert self.initialised_, 'Figure has not been initialised yet!'
# If label is not the current display_mode_,
# update figure
if self.display_mode_ != label:
self.display_mode_ = label
self._update_figure(axis_switch=False)
return
def _handle_ann_mode_radio(self,
label):
"""
Handle choice of annotation mode---foreground or background.
"""
# First, make sure the figure has been initialised.
assert self.initialised_, 'Figure has not been initialised yet!'
# If the chosen mode is the same as the current mode, nothing to do.
if self.ann_mode_ == label:
return
# Update the brush size for the current ann_mode_ first.
self.brush_sizes_[self.ann_mode_] = self.brush_size_
# Switch ann mode
self.ann_mode_ = label
# Retrieve the saved brush size.
self.brush_size_ = self.brush_sizes_[self.ann_mode_]
# Set the brush size slider appropriately
self.brush_size_slider_.set_val(self.brush_size_)
return
def _handle_axis_mode_radio(self,
label):
"""
Handle choice of viewing axis.
"""
# First make sure the figure is initialised.
assert self.initialised_, 'Figure has not been initialised yet!'
# If the chosen mode is the same as the current mode, there is nothing to do.
if self.view_axis_ == label:
return
# Else, switch the viewing axis and update the figure.
self.view_axis_ = label
# axis_switch is set to True here because we must readjust for axes.
self._update_figure(axis_switch=True)
return
def _handle_scroll_event(self,
event):
"""
Move along the viewing axis, up and down depending on whether
the wheel is scrolled up or down.
"""
# First, make sure the figure is initialised.
assert self.initialised_, 'Figure has not been initialised yet!'
# If the scroll happens on the brush size slider
if event.inaxes == self.ax_brush_size_:
if event.button == 'up':
self.brush_size_ = bound_low(self.brush_size_ - 2, 1)
elif event.button == 'down':
self.brush_size_ = bound_high(self.brush_size_ + 2, self.max_brush_size)
else:
return
self.brush_size_slider_.set_val(self.brush_size_)
return
# Else scroll along planes.
if self.view_axis_ == X:
if event.button == 'up':
if self.x_ > 0:
self.x_ -= 1
elif event.button == 'down':
if self.x_ < self.W - 1:
self.x_ += 1
else:
return
# Update the x slider as well. A '+ 1' is needed because on the slider, the
# slide numbers start from 0.
self.x_slider_.set_val(self.x_ + 1)
if self.view_axis_ == Y:
if event.button == 'up':
if self.y_ > 0:
self.y_ -= 1
elif event.button == 'down':
if self.y_ < self.H - 1:
self.y_ += 1
else:
return
# Update the y slider as well. A '+ 1' is needed because on the slider, the
# slide numbers start from 0.
self.y_slider_.set_val(self.y_ + 1)
if self.view_axis_ == Z:
if event.button == 'up':
if self.z_ > 0:
self.z_ -= 1
elif event.button == 'down':
if self.z_ < self.z_limits[1] - self.z_limits[0] - 1:
self.z_ += 1
else:
return
# Update the z slider as well. A '+ 1' is needed because on the slider, the
# slide numbers start from 0.
self.z_slider_.set_val(self.z_ + 1)
# Update figure to reflect the new image.
self._update_figure()
return
# Handle keyboard shortcuts.
def _handle_keyboard_shortcuts(self,
event):
"""
Handle keyboard shortcuts: Keyboard shortcuts let you switch
easily between annotation modes and other functions.
Currently, annotation modes are handled.
In the future, brush size is planned to be included.
"""
# First, make sure the figure has been initialised.
assert self.initialised_, 'Figure has not been initialised yet!'
if event.key not in RECOGNISED_KEYBOARD_SHORTCUTS:
return
if event.key in ANNO_KEYPRESS_DICT:
return self._handle_anno_keyboard_shorcuts(event.key)
if event.key in PLANES_KEYPRESS_DICT:
return self._handle_planes_keyboard_shortcuts(event.key)
if event.key in AXIS_KEYPRESS_DICT:
return self._handle_axis_keyboard_shortcuts(event.key)
if event.key in MOVE_KEYPRESS_DICT:
return self._handle_move_keyboard_shortcuts(event.key)
if event.key in ANNO_SEG_KEYPRESS_DICT:
return self._handle_anno_seg_keyboard_shortcuts(event.key)
# Can add other functions here.
return
def _handle_anno_keyboard_shorcuts(self,
key):
"""
Handle keyboard shortcuts for annotation modes.
"""
# First, make sure the figure has been initialised.
assert self.initialised_, 'Figure has not been initialised yet!'
label, index = ANNO_KEYPRESS_DICT[key]
self.ann_mode_ = label
self.ann_mode_radio_.set_active(index)
return
def _handle_axis_keyboard_shortcuts(self,
key):
"""
Handle keyboard shortcuts for viewing axis modes.
"""
# First, make sure the figure is initialised.
assert self.initialised_, 'Figure has not been initialised yet!'
label, index = AXIS_KEYPRESS_DICT[key]
if self.view_axis_ == label:
# Current viewing is already the same as the chosen one.
# Do nothing.
return
# Set the viewing axis.
self.view_axis_ = label
self.axis_mode_radio_.set_active(index)
# The figure needs to be updated too.
self._update_figure(axis_switch=True)
return
def _handle_planes_keyboard_shortcuts(self,
key):
"""
Handle keyboard shortcuts for planes.
Move along annotated planes depending on what shortcut was used.
"""
if key == 'z':
if self.z_ > 0:
z__ = self.z_ - 1
while z__ >= 0 and not self.annotated_planes_[z__]:
z__ -= 1
if z__ >= 0 and self.annotated_planes_[z__]:
self.z_ = z__
elif key == 'm':
if self.z_ < self.n_slices - 1:
z__ = self.z_ + 1
while z__ < self.n_slices and not self.annotated_planes_[z__]:
z__ += 1
if z__ < self.n_slices and self.annotated_planes_[z__]:
self.z_ = z__
# Update the z slider as well. A '+ 1' is needed because on the slider, the
# slide numbers start from 0.
self.z_slider_.set_val(self.z_ + 1)
# Update figure to reflect the new image.
self._update_figure()
return
def _handle_move_keyboard_shortcuts(self,
key):
"""
Handle moving along the image using keyboard shortcuts.
'up' and 'down' keys move in -1 and +1 along Y, respectively.
'left', and 'right' keys move in -1 and +1 along X, respectively.
"""
# First, make sure the figure is initialised.
assert self.initialised_, 'Figure has not been initialised yet!'
# Get the displacement from the MOVE_KEYPRESS_DICT
displacement = MOVE_KEYPRESS_DICT[key]
# Move in the image according to the displacement.
self.move_image(displacement=displacement, location=None)
return
def _handle_anno_seg_keyboard_shortcuts(self,
key):
"""
Handle selecting display mode---annotation or segmentation.
"""
# First, make sure the figure is initialised.
assert self.initialised_, 'Figure has not been initialised yet!'
# Get chosen display mode.
disp_mode, label = ANNO_SEG_KEYPRESS_DICT[key]
# If current display mode is different from key
if self.display_mode_ != disp_mode:
self.display_mode_ = disp_mode