-
Notifications
You must be signed in to change notification settings - Fork 13
/
annotations.py
2107 lines (1754 loc) · 67.3 KB
/
annotations.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
"""
Core utilities for rendering annotations on media.
@todo improve efficiency by minimizing number of times that images are copied
and rendered.
Copyright 2017-2023, Voxel51, Inc.
voxel51.com
"""
# pragma pylint: disable=redefined-builtin
# pragma pylint: disable=unused-wildcard-import
# pragma pylint: disable=wildcard-import
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from builtins import *
# pragma pylint: enable=redefined-builtin
# pragma pylint: enable=unused-wildcard-import
# pragma pylint: enable=wildcard-import
from copy import deepcopy
import logging
import random
import cv2
import numpy as np
from PIL import Image, ImageDraw, ImageFont
import eta
import eta.constants as etac
from eta.core.config import Config, Configurable
import eta.core.data as etad
import eta.core.frameutils as etaf
import eta.core.image as etai
import eta.core.logo as etal
import eta.core.utils as etau
import eta.core.video as etav
logger = logging.getLogger(__name__)
class AnnotationConfig(Config):
"""Configuration class that controls the look-and-feel of the annotations
rendered on images/videos.
Args:
show_frame_attr_names: (True) whether to render video/frame attribute
names, if available
show_frame_attr_confidences: (False) whether to render video/frame
attribute confidences, if available
frame_attrs_box_gap: ("1%") the gap between the frame attributes box
and the upper left corner of the image. This value is parsed by
``eta.core.image.Width(frame_attrs_box_gap)``
show_object_boxes: (True) whether to render object bounding boxes, if
available. If this is ``False``, labels, confidences, attributes,
etc. are also hidden
show_object_names: (True) whether to render object names, if available
show_object_labels: (True) whether to render object labels, if
available
show_object_attrs: (True) whether to render object attributes, if
available
show_object_confidences: (False) whether to render object label
confidences, if available
per_object_name_colors: (True) whether to render boxes for objects with
different names in different colors
per_object_label_colors: (True) whether to render boxes for objects
with different labels in different colors
per_object_index_colors: (True) whether to render boxes for objects
with different indexes in different colors
show_object_attr_names: (True) whether to render object attribute
names, if available
show_object_attr_confidences: (False) whether to render object
attribute confidences, if available
show_object_indices: (True) whether to render object indices, if
available
show_object_masks: (True) whether to render object segmentation masks,
if available
occluded_object_attr: ("occluded") the name of the boolean attribute
indicating whether an object is occluded
hide_occluded_objects: (False) whether to hide objects when they are
occluded
show_event_boxes: (True) whether to render event bounding boxes, if
available. If this is ``False``, all attributes, confidences, etc.
are also hidden
show_event_labels: (True) whether to render event labels, if available
show_event_attrs: (True) whether to render event attributes, if
available
show_event_names: (True) whether to render event names, if available
show_event_confidences: (False) whether to render event label
confidences, if available
per_event_name_colors: (True) whether to render boxes for events with
different names in different colors
per_event_label_colors: (True) whether to render boxes for events with
different labels in different colors
per_event_index_colors: (True) whether to render boxes for events with
different indexes in different colors
show_event_attr_names: (True) whether to render event attribute names,
if available
show_event_attr_confidences: (False) whether to render event attribute
confidences, if available
show_event_indices: (True) whether to render event indices, if
available. By default, this is ``True``
show_event_masks: (True) whether to render event segmentation masks, if
available
show_event_label_on_objects: (True) whether to render event labels as
attributes on objects that belong to events
show_event_objects_in_same_color: (True) whether to render objects that
belong to events in the same color as their parent event
occluded_event_attr: ("occluded") the name of the boolean attribute
indicating whether an event is occluded
hide_occluded_events: (False) whether to hide events when they are
occluded
bbox_alpha: (0.75) the transparency of bounding boxes
bbox_label_text_pad_pixels: (2) the padding, in pixels, around the text
in bounding box labels
bbox_linewidth: (3) the linewidth, in pixels, of bounding boxes
mask_border_thickness: (2) the thickness, in pixels, to use when
drawing the borders of segmentation masks
mask_fill_alpha: (0.7) the transparency of segmentation masks
show_frame_mask_semantics: (True) whether to render semantic labels for
frame mask regions, when mask indexes are available
attrs_box_render_method: ("panel") the method used to render object
attributes
attrs_box_bg_color: ("#000000") the background color for attributes
boxes
attrs_box_bg_alpha: (0.5) the transparency of attribute panel boxes
attrs_box_text_pad_pixels: (5) the padding, in pixels, around the text
in attribute boxes
attrs_box_text_line_spacing_pixels: (1) the padding, in pixels, between
each line of text in attribute boxes
show_keypoints_names: (False) whether to render keypoints names, if
available
show_keypoints_labels: (False) whether to render keypoints labels, if
available
show_keypoints_attrs: (False) whether to render keypoints attributes, if
available
show_keypoints_attr_names: (False) whether to render keypoint attribute
names, if available
show_keypoints_attr_confidences: (False) whether to render keypoint
attribute confidences, if available
per_keypoints_name_colors: (True) whether to render keypoints with
different names in different colors
per_keypoints_label_colors: (True) whether to render keypoints with
different labels in different colors
keypoints_size: (6) the size to render keypoints
keypoints_alpha: (0.75) the transparency of keypoints
keypoints_skeleton: (None) an optional keypoint skeleton dictionary of
the following form::
{
"labels": [
"left hand" "left shoulder", "right shoulder",
"right hand", "left eye", "right eye", "mouth"
],
"edges": [[0, 1, 2, 3], [4, 5, 6]],
}
draw_keypoints_skeletons: (True) whether to render keypoint skeletons,
if available
keypoints_edge_linewidth (2): the linewidth, in pixels, of keypoint
skeleton edges
keypoints_edge_alpha: (0.75) the transparency of keypoint skeleton
edges
show_polyline_names: (True) whether to render polyline names, if
available
show_polyline_labels: (True) whether to render polyline labels, if
available
show_polyline_attrs: (True) whether to render polyline attributes, if
available
show_polyline_attr_names: (True) whether to render polyline attribute
names, if available
show_polyline_attr_confidences: (False) whether to render polyline
attribute confidences, if available
hide_non_filled_polyline_annos: (False) whether to override other
settings and hide the annotation panels for non-filled polylines
(those with ``filled == False``)
per_polyline_name_colors: (True) whether to render polylines with
different names in different colors
per_polyline_label_colors: (True) whether to render polylines with
different labels in different colors
polyline_alpha: (0.75) the transparency of polylines
polyline_linewidth: (3) the linewidth, in pixels, of non-filled
polylines
fill_polylines: (True) whether to draw polylines as filled, when
possible
show_all_names: (False) whether to render all names, if available. If
set to ``True``, this overrides all other name flags
hide_all_names: (False) whether to hide all names, if available. If
set to ``True``, this overrides all other name flags
show_name_only_titles: (False) whether to render titles that only
contain the ``name`` of the entity (i.e., no label, confidence,
index, etc)
show_all_confidences: (False) whether to render all confidences, if
available. If set to ``True``, this overrides all other confidence
flags
hide_all_confidences: (False) whether to hide all confidences, if
available. If set to ``True``, this overrides all other confidence
flags
labels_whitelist: (None) an optional whitelist of labels (of any kind).
If provided, only entities whose ``label`` is in this list will be
rendered
labels_blacklist: (None) an optional list of labels (of any kind) to
not render
attr_names_blacklist: (None) an optional list of attribute names (of
any kind) to not render
attr_values_blacklist: (None) an optional list of attribute values (of
any kind) to not render
hide_false_boolean_attrs: (False) whether to hide attributes (of any
kind) when they are ``False``
confidence_scaled_alpha: (False) whether to scale alpha values of
objects and events based on their associated confidences
colormap_config: (None) the ``eta.core.annotations.ColormapConfig`` to
use to select colors for objects/event boxes
text_color: ("#FFFFFF") the annotation text color
font_path: (``eta.core.constants.DEFAULT_FONT_PATH``) the path to the
``PIL.ImageFont`` to use
font_size: (16) the font size to use
scale_by_media_height: (True) whether to scale font sizes and
linewidths according to the height of the media (relative to a
height of 720 pixels)
add_logo: (False) whether to add a logo to the frames
logo_config: (None) the ``eta.core.logo.LogoConfig`` describing the
logo to use
"""
def __init__(self, d):
# FRAME ATTRIBUTES ####################################################
self.show_frame_attr_names = self.parse_bool(
d, "show_frame_attr_names", default=True
)
self.show_frame_attr_confidences = self.parse_bool(
d, "show_frame_attr_confidences", default=False
)
self.frame_attrs_box_gap = self.parse_string(
d, "frame_attrs_box_gap", default="1%"
)
# OBJECTS #############################################################
self.show_object_boxes = self.parse_bool(
d, "show_object_boxes", default=True
)
self.show_object_names = self.parse_bool(
d, "show_object_names", default=True
)
self.show_object_labels = self.parse_bool(
d, "show_object_labels", default=True
)
self.show_object_attrs = self.parse_bool(
d, "show_object_attrs", default=True
)
self.show_object_confidences = self.parse_bool(
d, "show_object_confidences", default=False
)
self.per_object_name_colors = self.parse_bool(
d, "per_object_name_colors", default=True
)
self.per_object_label_colors = self.parse_bool(
d, "per_object_label_colors", default=True
)
self.per_object_index_colors = self.parse_bool(
d, "per_object_index_colors", default=True
)
self.show_object_attr_names = self.parse_bool(
d, "show_object_attr_names", default=True
)
self.show_object_attr_confidences = self.parse_bool(
d, "show_object_attr_confidences", default=False
)
self.show_object_indices = self.parse_bool(
d, "show_object_indices", default=True
)
self.show_object_masks = self.parse_bool(
d, "show_object_masks", default=True
)
self.occluded_object_attr = self.parse_string(
d, "occluded_object_attr", default="occluded"
)
self.hide_occluded_objects = self.parse_bool(
d, "hide_occluded_objects", default=False
)
# EVENTS ##############################################################
self.show_event_boxes = self.parse_bool(
d, "show_event_boxes", default=True
)
self.show_event_labels = self.parse_bool(
d, "show_event_labels", default=True
)
self.show_event_attrs = self.parse_bool(
d, "show_event_attrs", default=True
)
self.show_event_names = self.parse_bool(
d, "show_event_names", default=True
)
self.show_event_confidences = self.parse_bool(
d, "show_event_confidences", default=False
)
self.per_event_name_colors = self.parse_bool(
d, "per_event_name_colors", default=True
)
self.per_event_label_colors = self.parse_bool(
d, "per_event_label_colors", default=True
)
self.per_event_index_colors = self.parse_bool(
d, "per_event_index_colors", default=True
)
self.show_event_attr_names = self.parse_bool(
d, "show_event_attr_names", default=True
)
self.show_event_attr_confidences = self.parse_bool(
d, "show_event_attr_confidences", default=False
)
self.show_event_indices = self.parse_bool(
d, "show_event_indices", default=True
)
self.show_event_masks = self.parse_bool(
d, "show_event_masks", default=True
)
self.show_event_label_on_objects = self.parse_bool(
d, "show_event_label_on_objects", default=True
)
self.show_event_objects_in_same_color = self.parse_bool(
d, "show_event_objects_in_same_color", default=True
)
self.occluded_event_attr = self.parse_string(
d, "occluded_event_attr", default="occluded"
)
self.hide_occluded_events = self.parse_bool(
d, "hide_occluded_events", default=False
)
# BOUNDING BOXES ######################################################
self.bbox_alpha = self.parse_number(d, "bbox_alpha", default=0.75)
self.bbox_label_text_pad_pixels = self.parse_number(
d, "bbox_label_text_pad_pixels", default=2
)
self.bbox_linewidth = self.parse_number(d, "bbox_linewidth", default=3)
# MASKS ###############################################################
self.mask_border_thickness = self.parse_number(
d, "mask_border_thickness", default=2
)
self.mask_fill_alpha = self.parse_number(
d, "mask_fill_alpha", default=0.7
)
self.show_frame_mask_semantics = self.parse_bool(
d, "show_frame_mask_semantics", default=True
)
# ATTRIBUTE BOXES #####################################################
self.attrs_box_render_method = self.parse_categorical(
d, "attrs_box_render_method", ["list", "panel"], default="panel"
)
self.attrs_box_bg_color = self.parse_string(
d, "attrs_box_bg_color", default="#000000"
)
self.attrs_box_bg_alpha = self.parse_number(
d, "attrs_box_bg_alpha", default=0.5
)
self.attrs_box_text_pad_pixels = self.parse_number(
d, "attrs_box_text_pad_pixels", default=5
)
self.attrs_box_text_line_spacing_pixels = self.parse_number(
d, "attrs_box_text_line_spacing_pixels", default=1
)
# KEYPOINTS ###########################################################
self.show_keypoints_names = self.parse_bool(
d, "show_keypoints_names", default=False
)
self.show_keypoints_labels = self.parse_bool(
d, "show_keypoints_labels", default=False
)
self.show_keypoints_attrs = self.parse_bool(
d, "show_keypoints_attrs", default=False
)
self.show_keypoints_attr_names = self.parse_bool(
d, "show_keypoints_attr_names", default=False
)
self.show_keypoints_attr_confidences = self.parse_bool(
d, "show_keypoints_attr_confidences", default=False
)
self.per_keypoints_name_colors = self.parse_bool(
d, "per_keypoints_name_colors", default=True
)
self.per_keypoints_label_colors = self.parse_bool(
d, "per_keypoints_label_colors", default=True
)
self.keypoints_size = self.parse_number(d, "keypoints_size", default=6)
self.keypoints_alpha = self.parse_number(
d, "keypoints_alpha", default=0.75
)
self.keypoints_skeleton = self.parse_dict(
d, "keypoints_skeleton", default=None
)
self.draw_keypoints_skeletons = self.parse_bool(
d, "draw_keypoints_skeletons", default=True
)
self.keypoints_edge_linewidth = self.parse_number(
d, "keypoints_edge_linewidth", default=2
)
self.keypoints_edge_alpha = self.parse_number(
d, "keypoints_edge_alpha", default=0.75
)
# POLYLINES ###########################################################
self.show_polyline_names = self.parse_bool(
d, "show_polyline_names", default=True
)
self.show_polyline_labels = self.parse_bool(
d, "show_polyline_labels", default=True
)
self.show_polyline_attrs = self.parse_bool(
d, "show_polyline_attrs", default=True
)
self.show_polyline_attr_names = self.parse_bool(
d, "show_polyline_attr_names", default=True
)
self.show_polyline_attr_confidences = self.parse_bool(
d, "show_polyline_attr_confidences", default=False
)
self.hide_non_filled_polyline_annos = self.parse_bool(
d, "hide_non_filled_polyline_annos", default=False
)
self.per_polyline_name_colors = self.parse_bool(
d, "per_polyline_name_colors", default=True
)
self.per_polyline_label_colors = self.parse_bool(
d, "per_polyline_label_colors", default=True
)
self.polyline_alpha = self.parse_number(
d, "polyline_alpha", default=0.75
)
self.polyline_linewidth = self.parse_number(
d, "polyline_linewidth", default=3
)
self.fill_polylines = self.parse_bool(
d, "fill_polylines", default=True
)
# ALL LABELS ##########################################################
self.show_all_names = self.parse_bool(
d, "show_all_names", default=False
)
self.hide_all_names = self.parse_bool(
d, "hide_all_names", default=False
)
self.show_name_only_titles = self.parse_bool(
d, "show_name_only_titles", default=False
)
self.show_all_confidences = self.parse_bool(
d, "show_all_confidences", default=False
)
self.hide_all_confidences = self.parse_bool(
d, "hide_all_confidences", default=False
)
self.labels_whitelist = self.parse_array(
d, "labels_whitelist", default=None
)
self.labels_blacklist = self.parse_array(
d, "labels_blacklist", default=None
)
self.attr_names_blacklist = self.parse_array(
d, "attr_names_blacklist", default=None
)
self.attr_values_blacklist = self.parse_array(
d, "attr_values_blacklist", default=None
)
self.hide_false_boolean_attrs = self.parse_bool(
d, "hide_false_boolean_attrs", default=False
)
self.confidence_scaled_alpha = self.parse_bool(
d, "confidence_scaled_alpha", default=False
)
# FONTS AND COLORS ####################################################
self.colormap_config = self.parse_object(
d, "colormap_config", ColormapConfig, default=None
)
self.text_color = self.parse_string(d, "text_color", default="#FFFFFF")
self.font_path = self.parse_string(
d, "font_path", default=etac.DEFAULT_FONT_PATH
)
self.font_size = self.parse_number(d, "font_size", default=16)
self.scale_by_media_height = self.parse_bool(
d, "scale_by_media_height", default=True
)
# LOGO ################################################################
self.add_logo = self.parse_bool(d, "add_logo", default=False)
self.logo_config = self.parse_object(
d, "logo_config", etal.LogoConfig, default=None
)
self._media_height = None
self._scale_factor = None
self._logo = None
self._font = None
self._linewidth = None
self.set_media_size(frame_size=(1280, 720))
#
# Load Logo _after_ setting media size to avoid unnecessary rendering
# of the logo
#
if self.logo_config is not None:
self._logo = etal.Logo(self.logo_config)
elif self.add_logo:
self._logo = etal.Logo.load_default()
if self.colormap_config is not None:
self._colormap = self.colormap_config.build()
else:
self._colormap = Colormap.load_default()
@property
def scale_factor(self):
return self._scale_factor
@property
def colormap(self):
return self._colormap
@property
def media_height(self):
return self._media_height
@property
def font(self):
return self._font
@property
def linewidth(self):
return self._linewidth
@property
def logo(self):
return self._logo
def set_media_size(self, frame_size=None, shape=None, img=None):
"""Sets the size of the media to the given value. This allows for
optimizing font sizes, linewidths, and logo resolutions to suit the
dimensions of the media being annotated.
Exactly *one* keyword argument must be provided.
Args:
frame_size: the (width, height) of the image/video frame
shape: the (height, width, ...) of the image/video frame, e.g. from
img.shape
img: an example image/video frame
"""
frame_size = etai.to_frame_size(
frame_size=frame_size, shape=shape, img=img
)
# Set media height
self._media_height = frame_size[1]
# Set scale factor
self._scale_factor = self._get_media_scale_factor()
# Render logo, if necessary
if self.add_logo and self.logo is not None:
self._logo.render_for(frame_size=frame_size)
# Render font
font_size = int(round(self.scale_factor * self.font_size))
self._font = ImageFont.truetype(self.font_path, font_size)
# Render linewidth
self._linewidth = int(round(self.scale_factor * self.bbox_linewidth))
def _get_media_scale_factor(self):
if self.scale_by_media_height:
return self.media_height / 720.0
return 1.0
class ColormapConfig(Config):
"""Configuration class that encapsulates the name of a Colormap and an
instance of its associated Config class.
Attributes:
type: the fully-qualified class name of the Colormap, e.g.,
`core.utils.ManualColormap`
config: an instance of the Config class associated with the specified
Colormap (e.g., `core.utils.ManualColormapConfig`)
"""
def __init__(self, d):
self.type = self.parse_string(d, "type")
self._colormap_cls, config_cls = Configurable.parse(self.type)
self.config = self.parse_object(d, "config", config_cls)
def build(self):
"""Factory method that builds the Colormap instance from the config
specified by this class.
"""
return self._colormap_cls(self.config)
class Colormap(Configurable):
"""Class encapsulating a colormap."""
@property
def colors(self):
"""The array of hex colors in the colormap."""
raise NotImplementedError("subclass must implement colors")
def get_color(self, index):
"""Gets the color for the given index. Modular arithmetic is used, so
any integer is valid regardless of the colormap length.
"""
return self.colors[index % len(self.colors)]
@classmethod
def load_default(cls):
"""Loads the default Colormap."""
config = ShuffledHLSColormapConfig.builder().set(num_colors=36).build()
return ShuffledHLSColormap(config)
class ManualColormapConfig(Config):
"""Class that configures a ManualColormap."""
def __init__(self, d):
self.colors = self.parse_array(d, "colors")
class ManualColormap(Colormap):
"""A colormap with manually specified colors."""
def __init__(self, config):
"""Creates a ManualColormap instance.
Args:
config: a ManualColormapConfig instance
"""
self.validate(config)
self.config = config
@property
def colors(self):
"""The array of hex colors in the colormap."""
return self.config.colors
class ShuffledHLSColormapConfig(Config):
"""Class that configures an ShuffledHLSColormap."""
def __init__(self, d):
self.num_colors = self.parse_number(d, "num_colors")
self.lightness = self.parse_number(d, "lightness", default=0.4)
self.saturation = self.parse_number(d, "saturation", default=0.7)
self.seed = self.parse_number(d, "seed", default=42)
class ShuffledHLSColormap(Colormap):
"""A colormap with equally spaced (and randonly shuffled) hues in HLS
colorspace.
"""
def __init__(self, config):
"""Creates an ShuffledHLSColormap instance.
Args:
config: a ShuffledHLSColormapConfig instance
"""
self.validate(config)
self.config = config
self._colors = self._generate_colors(self.config.num_colors)
@property
def colors(self):
"""The array of hex colors in the colormap."""
return self._colors
def _generate_colors(self, num_hues):
hues = np.linspace(0, 1, num_hues + 1)[:-1]
colors = [
etai.hls_to_hex(hue, self.config.lightness, self.config.saturation)
for hue in hues
]
rng = random.Random(self.config.seed)
rng.shuffle(colors)
return colors
class Draw(object):
"""Context manager that allows for convenient, temporary conversion of a
numpy image into a `ImageDraw.Draw` instance when inside the context.
The input numpy array is modified in-place when the context manager exits.
"""
def __init__(self, img):
"""Creates a Draw instance.
Args:
img: an numpy image
"""
self._img = img
self._img_pil = None
def __enter__(self):
self._img_pil = Image.fromarray(self._img)
return ImageDraw.Draw(self._img_pil)
def __exit__(self, *args):
self._img[:] = np.asarray(self._img_pil)
def annotate_video(
input_path, video_labels, output_path, support=None, annotation_config=None
):
"""Annotates the video with the given labels.
Args:
input_path: the path to the video to annotate
video_labels: an `eta.core.video.VideoLabels` instance describing the
content to annotate
output_path: the path to write the output video
support: an optional `[first, last]` range of frames to render. By
default, the entire video is annotated
annotation_config: an optional AnnotationConfig specifying how to
render the annotations. If omitted, the default config is used
"""
if annotation_config is None:
annotation_config = _DEFAULT_ANNOTATION_CONFIG
# Render framewise labels for annotation
video_labels = video_labels.render_framewise()
mask_index = video_labels.mask_index
if support is not None:
frames = etaf.FrameRange(*support)
else:
frames = None
# Annotate video
with etav.VideoProcessor(
input_path, frames=frames, out_video_path=output_path
) as vp:
# Set media size
annotation_config.set_media_size(frame_size=vp.output_frame_size)
# Annotate frames
with etau.ProgressBar(iters_str="frames") as pb:
for img in pb(vp):
logger.debug("Annotating frame %d", vp.frame_number)
frame_labels = video_labels[vp.frame_number]
img_anno = _annotate_video_frame(
img,
frame_labels,
mask_index=mask_index,
annotation_config=annotation_config,
)
vp.write(img_anno)
def _annotate_video_frame(
img, frame_labels, mask_index=None, annotation_config=None
):
if annotation_config is None:
annotation_config = _DEFAULT_ANNOTATION_CONFIG
annotation_config.set_media_size(img=img)
return _annotate_image(
img, frame_labels, annotation_config, mask_index=mask_index
)
def annotate_image(img, frame_labels, annotation_config=None):
"""Annotates the image with the given labels.
Args:
img: the image to annotate
frame_labels: a FrameLabels describing the content to annotate
annotation_config: an optional AnnotationConfig specifying how to
render the annotations. If omitted, the default config is used
Returns:
the annotated image
"""
if annotation_config is None:
annotation_config = _DEFAULT_ANNOTATION_CONFIG
if etai.is_gray(img):
img = etai.gray_to_rgb(img)
# Set media size
annotation_config.set_media_size(img=img)
return _annotate_image(img, frame_labels, annotation_config)
def _annotate_image(img, frame_labels, annotation_config, mask_index=None):
# Parse config
attr_names_blacklist = annotation_config.attr_names_blacklist
attr_values_blacklist = annotation_config.attr_values_blacklist
hide_false_boolean_attrs = annotation_config.hide_false_boolean_attrs
show_attr_names = (
annotation_config.show_frame_attr_names
or annotation_config.show_all_names
) and not annotation_config.hide_all_names
show_frame_attr_confidences = (
annotation_config.show_frame_attr_confidences
or annotation_config.show_all_confidences
) and not annotation_config.hide_all_confidences
add_logo = annotation_config.add_logo
# Parse inputs
has_mask = frame_labels.has_mask
has_keypoints = frame_labels.has_keypoints
has_polylines = frame_labels.has_polylines
has_events = frame_labels.has_events
has_objects = frame_labels.has_objects
has_attributes = frame_labels.has_attributes
#
# Draw frame mask
#
if has_mask:
logger.debug("Rendering frame mask")
mask = frame_labels.mask
if frame_labels.has_mask_index:
mask_index = frame_labels.mask_index
img = _draw_frame_mask(
img, mask, annotation_config, mask_index=mask_index
)
#
# Draw polylines
#
if has_polylines:
logger.debug("Rendering %d polylines", len(frame_labels.polylines))
for polyline in frame_labels.polylines:
img = _draw_polyline(img, polyline, annotation_config)
#
# Draw keypoints
#
if has_keypoints:
logger.debug("Rendering %d keypoints", len(frame_labels.keypoints))
for keypoints in frame_labels.keypoints:
img = _draw_keypoints(img, keypoints, annotation_config)
#
# Draw events
#
event_attr_strs = []
if has_events:
logger.debug("Rendering %d events", len(frame_labels.events))
for event in frame_labels.events:
img, attr_strs = _draw_event(img, event, annotation_config)
event_attr_strs.extend(attr_strs)
#
# Draw objects
#
if has_objects:
logger.debug("Rendering %d objects", len(frame_labels.objects))
for obj in frame_labels.objects:
img = _draw_object(img, obj, annotation_config)
#
# Draw attributes panel
#
if has_attributes or event_attr_strs:
attr_strs = []
if has_attributes:
# Alphabetize
frame_labels.attrs.sort_by_name()
# Render attributes
attr_strs.extend(
_render_attrs(
frame_labels.attrs,
attr_names_blacklist,
attr_values_blacklist,
hide_false_boolean_attrs,
show_attr_names,
show_frame_attr_confidences,
)
)
# Append any event-level attributes
# @todo visually separate these from other attributes?
attr_strs.extend(event_attr_strs)
# Draw attributes
if attr_strs:
logger.debug("Rendering %d frame attributes", len(attr_strs))
img = _draw_frame_attrs(img, attr_strs, annotation_config)
#
# Draw logo
#
if add_logo:
logger.debug("Rendering logo")
img = _draw_logo(img, annotation_config)
return img
def _draw_logo(img, annotation_config):
logo = annotation_config.logo
return logo.apply(img)
def _draw_polyline(img, polyline, annotation_config):
# Parse config
show_name = (
annotation_config.show_polyline_names
or annotation_config.show_all_names
) and not annotation_config.hide_all_names
show_label = annotation_config.show_polyline_labels
show_name_only_titles = annotation_config.show_name_only_titles
show_attrs = annotation_config.show_polyline_attrs
show_attr_names = (
annotation_config.show_polyline_attr_names
or annotation_config.show_all_names
) and not annotation_config.hide_all_names
show_attr_confidences = (
annotation_config.show_polyline_attr_confidences
or annotation_config.show_all_confidences
) and not annotation_config.hide_all_confidences
attr_names_blacklist = annotation_config.attr_names_blacklist
attr_values_blacklist = annotation_config.attr_values_blacklist
hide_false_boolean_attrs = annotation_config.hide_false_boolean_attrs
labels_whitelist = annotation_config.labels_whitelist
labels_blacklist = annotation_config.labels_blacklist
per_name_colors = annotation_config.per_polyline_name_colors
per_label_colors = annotation_config.per_polyline_label_colors
alpha = annotation_config.polyline_alpha
thickness = int(
round(
annotation_config.scale_factor
* annotation_config.polyline_linewidth
)
)
gap = annotation_config.linewidth
fill_polylines = annotation_config.fill_polylines
hide_non_filled_polyline_annos = (
annotation_config.hide_non_filled_polyline_annos
)
colormap = annotation_config.colormap
has_attributes = polyline.has_attributes
#
# Check for immediate return
#
return_now = False
# Check labels whitelist
if labels_whitelist is not None:
if polyline.label not in labels_whitelist:
return_now = True
# Check labels blacklist
if labels_blacklist is not None:
if polyline.label in labels_blacklist:
return_now = True
if not polyline.has_vertices:
return_now = True
if return_now:
return img