-
Notifications
You must be signed in to change notification settings - Fork 3.8k
Expand file tree
/
Copy pathannotations-collection.ts
More file actions
1415 lines (1263 loc) · 56.8 KB
/
Copy pathannotations-collection.ts
File metadata and controls
1415 lines (1263 loc) · 56.8 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
// Copyright (C) 2019-2022 Intel Corporation
// Copyright (C) CVAT.ai Corporation
//
// SPDX-License-Identifier: MIT
import {
shapeFactory, trackFactory, Track, Shape, Tag,
MaskShape, BasicInjection, SkeletonShape,
SkeletonTrack, PolygonShape, CuboidShape,
RectangleShape, PolylineShape, PointsShape, EllipseShape,
InterpolationNotPossibleError,
} from './annotations-objects';
import { SerializedCollection, SerializedShape, SerializedTrack } from './server-response-types';
import AnnotationsFilter from './annotations-filter';
import { checkObjectType } from './common';
import Statistics from './statistics';
import { Attribute, Label } from './labels';
import { ArgumentError, ScriptingError } from './exceptions';
import ObjectState from './object-state';
import { cropMask } from './object-utils';
import config from './config';
import {
HistoryActions, ShapeType, ObjectType, colors, Source, DimensionType, JobType,
} from './enums';
import AnnotationHistory from './annotations-history';
const validateAttributesList = (
attributes: { spec_id: number, value: string }[],
): { spec_id: number, value: string }[] => {
for (const { spec_id: specID, value } of attributes) {
checkObjectType('attribute id', specID, 'integer', null);
checkObjectType('attribute value', value, 'string', null);
}
return attributes;
};
const objectAttributesAsList = (state: ObjectState): { spec_id: number, value: string }[] => (
Object.entries(state.attributes).map(([key, value]) => ({
spec_id: +key,
value,
}))
);
const labelAttributesAsDict = (label: Label): Record<number, Attribute> => (
label.attributes.reduce((accumulator, attribute) => {
accumulator[attribute.id] = attribute;
return accumulator;
}, {})
);
export default class Collection {
public flush: boolean;
private stopFrame: number;
private labels: Record<number, Label>;
private annotationsFilter: AnnotationsFilter;
private history: AnnotationHistory;
private shapes: Record<number, Shape[]>;
private tags: Record<number, Tag[]>;
private tracks: Track[];
private objects: Record<number, Shape | Tag | Track>;
private groups: { max: number };
private injection: BasicInjection;
constructor(data: {
labels: Label[];
history: AnnotationHistory;
stopFrame: number;
dimension: DimensionType;
framesInfo: BasicInjection['framesInfo'];
jobType: JobType;
consensusReplicas?: number;
}) {
this.stopFrame = data.stopFrame;
this.labels = data.labels.reduce((labelAccumulator, label) => {
labelAccumulator[label.id] = label;
(label?.structure?.sublabels || []).forEach((sublabel) => {
labelAccumulator[sublabel.id] = sublabel;
});
return labelAccumulator;
}, {});
this.annotationsFilter = new AnnotationsFilter();
this.history = data.history;
this.shapes = {}; // key is a frame
this.tags = {}; // key is a frame
this.tracks = [];
this.objects = {}; // key is a client id
this.flush = false;
this.groups = {
max: 0,
}; // it is an object to we can pass it as an argument by a reference
this.injection = {
labels: this.labels,
groups: this.groups,
framesInfo: data.framesInfo,
history: this.history,
dimension: data.dimension,
jobType: data.jobType,
groupColors: {},
nextClientID: () => ++config.globalObjectsCounter,
getMasksOnFrame: (frame: number) => (this.shapes[frame] as MaskShape[])
.filter((object) => object instanceof MaskShape),
consensusReplicas: data.consensusReplicas,
};
}
public import(data: Omit<SerializedCollection, 'version'>): {
tags: Tag[];
shapes: Shape[];
tracks: Track[];
} {
const result = {
tags: [],
shapes: [],
tracks: [],
};
for (const tag of data.tags) {
const clientID = this.injection.nextClientID();
const color = colors[clientID % colors.length];
const tagModel = new Tag(tag, clientID, color, this.injection);
this.tags[tagModel.frame] = this.tags[tagModel.frame] || [];
this.tags[tagModel.frame].push(tagModel);
this.objects[clientID] = tagModel;
result.tags.push(tagModel);
}
for (const shape of data.shapes) {
const clientID = this.injection.nextClientID();
const shapeModel = shapeFactory(shape, clientID, this.injection);
this.shapes[shapeModel.frame] = this.shapes[shapeModel.frame] || [];
this.shapes[shapeModel.frame].push(shapeModel);
this.objects[clientID] = shapeModel;
result.shapes.push(shapeModel);
}
for (const track of data.tracks) {
const clientID = this.injection.nextClientID();
const trackModel = trackFactory(track, clientID, this.injection);
// The function can return null if track doesn't have any shapes.
// In this case a corresponded message will be sent to the console
if (trackModel) {
this.tracks.push(trackModel);
result.tracks.push(trackModel);
this.objects[clientID] = trackModel;
}
}
return result;
}
public commit(
appended: Omit<SerializedCollection, 'version'>,
removed: Omit<SerializedCollection, 'version'>,
frame: number,
): { tags: Tag[]; shapes: Shape[]; tracks: Track[]; } {
const isCollectionConsistent = [].concat(removed.shapes, removed.tags, removed.tracks)
.every((object) => typeof object.clientID === 'number' &&
Object.prototype.hasOwnProperty.call(this.objects, object.clientID));
if (!isCollectionConsistent) {
throw new ArgumentError('Objects required to be deleted were not found in the collection');
}
const removedCollection: (Shape | Tag | Track)[] = [].concat(removed.shapes, removed.tags, removed.tracks)
.map((object) => this.objects[object.clientID as number]);
const imported = this.import(appended);
const appendedCollection = ([] as (Shape | Tag | Track)[])
.concat(imported.shapes, imported.tags, imported.tracks);
if (!(appendedCollection.length > 0 || removedCollection.length > 0)) {
// nothing to commit
return;
}
let prevRemoved = [];
removedCollection.forEach((collectionObject) => {
prevRemoved.push(collectionObject.removed);
collectionObject.removed = true;
});
this.history.do(
HistoryActions.COMMIT_ANNOTATIONS,
() => {
removedCollection.forEach((collectionObject, idx) => {
collectionObject.removed = prevRemoved[idx];
});
prevRemoved = [];
appendedCollection.forEach((collectionObject) => {
collectionObject.removed = true;
});
},
() => {
removedCollection.forEach((collectionObject) => {
prevRemoved.push(collectionObject.removed);
collectionObject.removed = true;
});
appendedCollection.forEach((collectionObject) => {
collectionObject.removed = false;
});
},
[].concat(
removedCollection.map((object) => object.clientID),
appendedCollection.map((object) => object.clientID),
),
frame,
);
}
public export(): Pick<SerializedCollection, 'shapes' | 'tracks' | 'tags'> {
const data = {
tracks: this.tracks.filter((track) => !track.removed)
.map((track) => track.toJSON() as SerializedTrack),
shapes: Object.values(this.shapes)
.reduce((accumulator, frameShapes) => {
accumulator.push(...frameShapes);
return accumulator;
}, [])
.filter((shape) => !shape.removed)
.map((shape) => shape.toJSON() as SerializedShape),
tags: Object.values(this.tags)
.reduce((accumulator, frameTags) => {
accumulator.push(...frameTags);
return accumulator;
}, [])
.filter((tag) => !tag.removed)
.map((tag) => tag.toJSON()),
};
return data;
}
public get(frame: number, allTracks: boolean, filters: object[]): ObjectState[] {
if (this.injection.framesInfo.isFrameDeleted(frame)) {
return [];
}
const { tracks } = this;
const shapes = this.shapes[frame] ?? [];
const tags = this.tags[frame] ?? [];
const objects = [].concat(tracks, shapes, tags);
const visible = [];
for (const object of objects) {
if (object.removed) {
continue;
}
try {
const stateData = object.get(frame);
if (stateData.outside && !stateData.keyframe && !allTracks && object instanceof Track) {
continue;
}
visible.push(stateData);
} catch (error: unknown) {
if (!(error instanceof InterpolationNotPossibleError)) {
throw error;
}
}
}
const objectStates = [];
const filtered = this.annotationsFilter.filterSerializedObjectStates(visible, filters);
visible.forEach((stateData) => {
if (!filters.length || filtered.includes(stateData.clientID)) {
const objectState = new ObjectState(stateData);
objectStates.push(objectState);
}
});
return objectStates;
}
private _mergeInternal(objectsForMerge: (Track | Shape)[], shapeType: ShapeType, label: Label): SerializedTrack {
const keyframes: Record<number, SerializedTrack['shapes'][0]> = {}; // frame: position
const elements = {}; // element_sublabel_id: [element], each sublabel will be merged recursively
if (!Object.values(ShapeType).includes(shapeType)) {
throw new ArgumentError(`Got unknown shapeType "${shapeType}"`);
}
const labelAttributes = labelAttributesAsDict(label);
for (let i = 0; i < objectsForMerge.length; i++) {
// For each state get corresponding object
const object = objectsForMerge[i];
if (object.label.id !== label.id) {
throw new ArgumentError(
`All object labels are expected to be "${label.name}", but got "${object.label.name}"`,
);
}
if (object.shapeType !== shapeType) {
throw new ArgumentError(
`All shapes are expected to be "${shapeType}", but got "${object.shapeType}"`,
);
}
// If this object is shape, get it position and save as a keyframe
if (object instanceof Shape) {
// Frame already saved and it is not outside
if (object.frame in keyframes && !keyframes[object.frame].outside) {
throw new ArgumentError('Expected only one visible shape per frame');
}
keyframes[object.frame] = {
type: shapeType,
frame: object.frame,
points: object.shapeType === ShapeType.SKELETON ? undefined : [...object.points],
occluded: object.occluded,
rotation: object.rotation,
z_order: object.zOrder,
outside: false,
attributes: Object.keys(object.attributes).reduce((accumulator, attrID) => {
// We save only mutable attributes inside a keyframe
if (attrID in labelAttributes && labelAttributes[attrID].mutable) {
accumulator.push({
spec_id: +attrID,
value: object.attributes[attrID],
});
}
return accumulator;
}, []),
};
// Push outside shape after each annotation shape
// Any not outside shape will rewrite it later
if (!(object.frame + 1 in keyframes) && object.frame + 1 <= this.stopFrame) {
keyframes[object.frame + 1] = JSON.parse(JSON.stringify(keyframes[object.frame]));
keyframes[object.frame + 1].outside = true;
keyframes[object.frame + 1].frame++;
keyframes[object.frame + 1].attributes = [];
(keyframes[object.frame + 1].elements || []).forEach((el) => {
el.outside = keyframes[object.frame + 1].outside;
el.frame = keyframes[object.frame + 1].frame;
});
}
} else if (object instanceof Track) {
// If this object is a track, iterate through all its
// keyframes and push copies to new keyframes
const attributes = {}; // id:value
const trackShapes = object.shapes;
for (const keyframe of Object.keys(trackShapes)) {
const shape = trackShapes[keyframe];
// Frame already saved and it is not outside
if (keyframe in keyframes && !keyframes[keyframe].outside) {
// This shape is outside and non-outside shape already exists
if (shape.outside) {
continue;
}
throw new ArgumentError('Expected only one visible shape per frame');
}
// We do not save an attribute if it has the same value
// We save only updates
let updatedAttributes = false;
for (const attrID in shape.attributes) {
if (!(attrID in attributes) || attributes[attrID] !== shape.attributes[attrID]) {
updatedAttributes = true;
attributes[attrID] = shape.attributes[attrID];
}
}
keyframes[keyframe] = {
type: shapeType,
frame: +keyframe,
points: object.shapeType === ShapeType.SKELETON ? undefined : [...shape.points],
rotation: shape.rotation,
occluded: shape.occluded,
outside: shape.outside,
z_order: shape.zOrder,
attributes: updatedAttributes ? Object.keys(attributes).reduce((accumulator, attrID) => {
accumulator.push({
spec_id: +attrID,
value: attributes[attrID],
});
return accumulator;
}, []) : [],
};
}
} else {
throw new ArgumentError(
'Trying to merge unknown object type. Only shapes and tracks are expected.',
);
}
if (object.shapeType === ShapeType.SKELETON) {
for (const element of (object as unknown as SkeletonShape | SkeletonTrack).elements) {
// for each track/shape element get its first objectState and keep it
elements[element.label.id] = [
...(elements[element.label.id] || []), element,
];
}
}
}
const mergedElements = [];
if (shapeType === ShapeType.SKELETON) {
for (const sublabel of label.structure.sublabels) {
if (!(sublabel.id in elements)) {
throw new ArgumentError(
`Merged skeleton is absent some of its elements (sublabel id: ${sublabel.id})`,
);
}
try {
mergedElements.push(this._mergeInternal(
elements[sublabel.id], elements[sublabel.id][0].shapeType, sublabel,
));
} catch (error) {
throw new ArgumentError(
`Could not merge some skeleton parts (sublabel id: ${sublabel.id}).
Original error is ${error.toString()}`,
);
}
}
}
let firstNonOutside = false;
for (const frame of Object.keys(keyframes).sort((a, b) => +a - +b)) {
// Remove all outside frames at the begin
firstNonOutside = firstNonOutside || keyframes[frame].outside;
if (!firstNonOutside && keyframes[frame].outside) {
delete keyframes[frame];
} else {
break;
}
}
const track = {
frame: Math.min.apply(
null,
Object.keys(keyframes).map((frame) => +frame),
),
shapes: Object.values(keyframes),
elements: shapeType === ShapeType.SKELETON ? mergedElements : undefined,
group: 0,
source: Source.MANUAL,
label_id: label.id,
attributes: Object.keys(objectsForMerge[0].attributes).reduce((accumulator, attrID) => {
if (!labelAttributes[attrID].mutable) {
accumulator.push({
spec_id: +attrID,
value: objectsForMerge[0].attributes[attrID],
});
}
return accumulator;
}, []),
};
return track;
}
public merge(objectStates: ObjectState[]): void {
checkObjectType('shapes to merge', objectStates, null, { cls: Array, name: 'Array' });
if (!objectStates.length) return;
const objectsForMerge = objectStates.map((state) => {
checkObjectType('object state', state, null, { cls: ObjectState, name: 'ObjectState' });
const object = this.objects[state.clientID];
if (typeof object === 'undefined') {
throw new ArgumentError(
'The object is not in collection yet. Call ObjectState.put([state]) before you can merge it',
);
}
if (state.shapeType === ShapeType.MASK) {
throw new ArgumentError(
'Merging for masks is not supported',
);
}
return object;
});
const { label, shapeType } = objectStates[0];
if (!(label.id in this.labels)) {
throw new ArgumentError(`Unknown label for the task: ${label.id}`);
}
const track = this._mergeInternal(objectsForMerge as (Shape | Track)[], shapeType, label);
const imported = this.import({
tracks: [track],
tags: [],
shapes: [],
});
// Remove other shapes
for (const object of objectsForMerge) {
object.removed = true;
}
const [importedTrack] = imported.tracks;
this.history.do(
HistoryActions.MERGED_OBJECTS,
() => {
importedTrack.removed = true;
for (const object of objectsForMerge) {
object.removed = false;
}
},
() => {
importedTrack.removed = false;
for (const object of objectsForMerge) {
object.removed = true;
}
},
[...objectsForMerge.map((object) => object.clientID), importedTrack.clientID],
objectStates[0].frame,
);
}
private _splitInternal(objectState: ObjectState, object: Track, frame: number): SerializedTrack[] {
const labelAttributes = labelAttributesAsDict(object.label);
// first clear all server ids which may exist in the object being splitted
const copy = trackFactory(object.toJSON(), -1, this.injection);
copy.clearServerID();
const exported = copy.toJSON();
// then create two copies, before this frame and after this frame
const prev = {
frame: exported.frame,
group: 0,
label_id: exported.label_id,
attributes: exported.attributes,
shapes: [],
source: Source.MANUAL,
elements: [],
};
// after this frame copy is almost the same, except of starting frame
const next = JSON.parse(JSON.stringify(prev));
next.frame = frame;
// get position of the object on a frame where user does split and push it to next shape
const position = {
type: objectState.shapeType,
points: objectState.shapeType === ShapeType.SKELETON ? undefined : [...objectState.points],
rotation: objectState.rotation,
occluded: objectState.occluded,
outside: objectState.outside,
z_order: objectState.zOrder,
attributes: Object.keys(objectState.attributes).reduce((accumulator, attrID) => {
if (labelAttributes[attrID].mutable) {
accumulator.push({
spec_id: +attrID,
value: objectState.attributes[attrID],
});
}
return accumulator;
}, []),
frame,
};
next.shapes.push(JSON.parse(JSON.stringify(position)));
// split all shapes of an initial object into two groups (before/after the frame)
exported.shapes.forEach((shape) => {
if (shape.frame < frame) {
prev.shapes.push(JSON.parse(JSON.stringify(shape)));
} else if (shape.frame > frame) {
next.shapes.push(JSON.parse(JSON.stringify(shape)));
}
});
prev.shapes.push(JSON.parse(JSON.stringify(position)));
prev.shapes[prev.shapes.length - 1].outside = true;
// do the same recursively for all object elements if there are any
if (object instanceof SkeletonTrack) {
objectState.elements.forEach((elementState, idx) => {
const elementObject = object.elements[idx];
const [prevEl, nextEl] = this._splitInternal(elementState, elementObject, frame);
prev.elements.push(prevEl);
next.elements.push(nextEl);
});
}
return [prev, next];
}
public split(objectState: ObjectState, frame: number): void {
checkObjectType('object state', objectState, null, { cls: ObjectState, name: 'ObjectState' });
checkObjectType('frame', frame, 'integer', null);
const object = this.objects[objectState.clientID] as Track;
if (typeof object === 'undefined') {
throw new ArgumentError('The object has not been saved yet. Call annotations.put([state]) before');
}
if (objectState.objectType !== ObjectType.TRACK) return;
const keyframes = Object.keys(object.shapes).sort((a, b) => +a - +b);
if (frame <= +keyframes[0]) return;
const [prev, next] = this._splitInternal(objectState, object, frame);
const imported = this.import({
tracks: [prev, next],
tags: [],
shapes: [],
});
// Remove source object
object.removed = true;
const [prevImported, nextImported] = imported.tracks;
this.history.do(
HistoryActions.SPLITTED_TRACK,
() => {
object.removed = false;
prevImported.removed = true;
nextImported.removed = true;
},
() => {
object.removed = true;
prevImported.removed = false;
nextImported.removed = false;
},
[object.clientID, prevImported.clientID, nextImported.clientID],
frame,
);
}
public group(objectStates: ObjectState[], reset: boolean): number {
checkObjectType('shapes to group', objectStates, null, { cls: Array, name: 'Array' });
const objectsForGroup = objectStates.map((state) => {
checkObjectType('object state', state, null, { cls: ObjectState, name: 'ObjectState' });
const object = this.objects[state.clientID];
if (typeof object === 'undefined') {
throw new ArgumentError('The object has not been saved yet. Call annotations.put([state]) before');
}
return object;
});
const groupIdx = reset ? 0 : ++this.groups.max;
const undoGroups = objectsForGroup.map((object) => object.group);
for (const object of objectsForGroup) {
object.group = groupIdx;
object.updated = Date.now();
}
const redoGroups = objectsForGroup.map((object) => object.group);
this.history.do(
HistoryActions.GROUPED_OBJECTS,
() => {
objectsForGroup.forEach((object, idx) => {
object.group = undoGroups[idx];
object.updated = Date.now();
});
},
() => {
objectsForGroup.forEach((object, idx) => {
object.group = redoGroups[idx];
object.updated = Date.now();
});
},
objectsForGroup.map((object) => object.clientID),
objectStates[0].frame,
);
return groupIdx;
}
public join(objectStates: ObjectState[], points: number[]): void {
checkObjectType('shapes to join', objectStates, null, { cls: Array, name: 'Array' });
checkObjectType('joined rle mask', points, null, { cls: Array, name: 'Array' });
if (objectStates.some((state, idx) => idx && state.frame !== objectStates[idx - 1].frame)) {
throw new ArgumentError('All joined objects must be placed on the same frame');
}
if (objectStates.some((state, idx) => idx && state.label.id !== objectStates[idx - 1].label.id)) {
throw new ArgumentError('All the objects must have the same label');
}
const objectsToJoin = objectStates.map((state) => {
checkObjectType('object state', state, null, { cls: ObjectState, name: 'ObjectState' });
const object = this.objects[state.clientID];
if (typeof object === 'undefined') {
throw new ArgumentError('The object has not been saved yet. Call annotations.put([state]) before');
}
if (!(object instanceof MaskShape)) {
throw new ArgumentError('Only shape masks can be joined');
}
return object;
});
if (objectsToJoin.length > 1) {
const rle = points;
const labelAttributes = labelAttributesAsDict(objectsToJoin[0].label);
const attrValues = validateAttributesList(objectAttributesAsList(objectStates[0]));
for (const attr of attrValues) {
if (objectStates.some((state) => state.attributes[attr.spec_id] !== attr.value)) {
attr.value = labelAttributes[attr.spec_id].defaultValue;
}
}
// Append newly created object to the collection
const imported = this.import({
shapes: [{
attributes: attrValues,
frame: objectsToJoin[0].frame,
group: 0,
label_id: objectsToJoin[0].label.id,
outside: false,
occluded: objectsToJoin.some((object: MaskShape) => object.occluded),
points: rle,
rotation: 0,
type: ShapeType.MASK,
z_order: Math.max(...objectsToJoin.map((object: MaskShape) => object.zOrder)),
source: Source.MANUAL,
elements: [],
}],
tracks: [],
tags: [],
});
// and remove joined shapes
for (const object of objectsToJoin) {
object.removed = true;
}
// handle history actions
const [importedShape] = imported.shapes;
this.history.do(
HistoryActions.JOINED_OBJECTS,
() => {
importedShape.removed = true;
for (const object of objectsToJoin) {
object.removed = false;
}
},
() => {
importedShape.removed = false;
for (const object of objectsToJoin) {
object.removed = true;
}
},
[...objectsToJoin.map((object) => object.clientID), importedShape.clientID],
objectsToJoin[0].frame,
);
}
}
public slice(state: ObjectState, results: number[][]): void {
if (results.length !== 2) {
throw new Error('Not supported slicing count');
}
const [points1, points2] = results;
checkObjectType('sliced object', state, null, { cls: ObjectState, name: 'ObjectState' });
checkObjectType('first slicing contour', points1, null, { cls: Array, name: 'Array' });
checkObjectType('second slicing contour', points2, null, { cls: Array, name: 'Array' });
points1.forEach(
(el: number) => checkObjectType('first slicing contour element', el, 'number'),
);
points2.forEach(
(el: number) => checkObjectType('second slicing contour element', el, 'number'),
);
const slicedObject = this.objects[state.clientID];
if (!(slicedObject instanceof PolygonShape || slicedObject instanceof MaskShape)) {
throw new ArgumentError('Only polygon shape or mask shape can be sliced');
}
const { width, height } = this.injection.framesInfo[slicedObject.frame];
if (slicedObject instanceof MaskShape) {
points1.push(slicedObject.left, slicedObject.top, slicedObject.right, slicedObject.bottom);
points2.push(slicedObject.left, slicedObject.top, slicedObject.right, slicedObject.bottom);
}
const imported = this.import({
shapes: [{
attributes: validateAttributesList(objectAttributesAsList(state)),
frame: slicedObject.frame,
group: slicedObject.group,
label_id: slicedObject.label.id,
outside: false,
occluded: slicedObject.occluded,
points: slicedObject.shapeType === ShapeType.POLYGON ?
points1 : cropMask(points1, width, height),
rotation: 0,
type: slicedObject.shapeType,
z_order: slicedObject.zOrder,
source: Source.MANUAL,
elements: [],
}, {
attributes: validateAttributesList(objectAttributesAsList(state)),
frame: slicedObject.frame,
group: slicedObject.group,
label_id: slicedObject.label.id,
outside: false,
occluded: slicedObject.occluded,
points: slicedObject.shapeType === ShapeType.POLYGON ?
points2 : cropMask(points2, width, height),
rotation: 0,
type: slicedObject.shapeType,
z_order: slicedObject.zOrder,
source: Source.MANUAL,
elements: [],
}],
tracks: [],
tags: [],
});
slicedObject.removed = true;
this.history.do(
HistoryActions.SLICED_OBJECT,
() => {
slicedObject.removed = false;
imported.shapes.forEach((shape) => {
shape.removed = true;
});
},
() => {
slicedObject.removed = true;
imported.shapes.forEach((shape) => {
shape.removed = false;
});
},
[...imported.shapes.map((object) => object.clientID), slicedObject.clientID],
slicedObject.frame,
);
}
public clear(options?: {
startFrame?: number;
stopFrame?: number;
delTrackKeyframesOnly?: boolean;
}): void {
const { startFrame, stopFrame, delTrackKeyframesOnly } = options ?? {};
if (typeof startFrame === 'undefined' && typeof stopFrame === 'undefined') {
this.shapes = {};
this.tags = {};
this.tracks = [];
this.objects = {};
this.flush = true;
} else {
const from = startFrame ?? 0;
const to = stopFrame ?? this.stopFrame;
// If only a range of annotations need to be cleared
for (let frame = from; frame <= to; frame++) {
this.shapes[frame] = [];
this.tags[frame] = [];
}
this.tracks.slice(0).forEach((track) => {
if (track.frame <= to) {
if (delTrackKeyframesOnly) {
for (const keyframe of Object.keys(track.shapes)) {
if (+keyframe >= from && +keyframe <= to) {
delete track.shapes[keyframe];
if (track instanceof SkeletonTrack) {
track.elements.forEach((element) => {
if (keyframe in element.shapes) {
delete element.shapes[keyframe];
element.updated = Date.now();
}
});
}
track.updated = Date.now();
}
}
if (Object.keys(track.shapes).length === 0) {
this.tracks.splice(this.tracks.indexOf(track), 1);
}
} else if (track.frame >= from) {
this.tracks.splice(this.tracks.indexOf(track), 1);
}
}
});
}
}
public statistics(): Statistics {
const labels = {};
const shapes = ['rectangle', 'polygon', 'polyline', 'points', 'ellipse', 'cuboid', 'skeleton'];
const body = {
...(shapes.reduce((acc, val) => ({
...acc,
[val]: { shape: 0, track: 0 },
}), {})),
mask: { shape: 0 },
tag: 0,
manually: 0,
interpolated: 0,
total: 0,
};
const sep = '{{cvat.skeleton.lbl.sep}}';
const fillBody = (spec, prefix = ''): void => {
const pref = prefix ? `${prefix}${sep}` : '';
for (const label of spec) {
const { name } = label;
labels[`${pref}${name}`] = JSON.parse(JSON.stringify(body));
if (label?.structure?.sublabels) {
fillBody(label.structure.sublabels, `${pref}${name}`);
}
}
};
const total = JSON.parse(JSON.stringify(body));
fillBody(Object.values(this.labels).filter((label) => !label.hasParent));
const scanTrack = (track, prefix = ''): void => {
const countInterpolatedFrames = (start: number, stop: number, lastIsKeyframe: boolean): number => {
let count = stop - start;
if (lastIsKeyframe) {
count -= 1;
}
for (let i = start + 1; lastIsKeyframe ? i < stop : i <= stop; i++) {
if (this.injection.framesInfo.isFrameDeleted(i)) {
count--;
}
}
return count;
};
const pref = prefix ? `${prefix}${sep}` : '';
const label = `${pref}${track.label.name}`;
labels[label][track.shapeType].track++;
const keyframes = Object.keys(track.shapes)
.sort((a, b) => +a - +b)
.map((el) => +el)
.filter((frame) => !this.injection.framesInfo.isFrameDeleted(frame));
if (!keyframes.length) {
return;
}
let prevKeyframe = keyframes[0];
let visible = false;
for (const keyframe of keyframes) {
if (visible) {
const interpolated = countInterpolatedFrames(prevKeyframe, keyframe, true);
labels[label].interpolated += interpolated;
labels[label].total += interpolated;
}
visible = !track.shapes[keyframe].outside;
prevKeyframe = keyframe;
if (visible) {
labels[label].manually++;
labels[label].total++;
}
}
let lastKey = keyframes[keyframes.length - 1];
if (track.shapeType === ShapeType.SKELETON) {
track.elements.forEach((element) => {
scanTrack(element, label);
lastKey = Math.max(lastKey, ...Object.keys(element.shapes).map((key) => +key));
});
}
if (lastKey !== this.stopFrame && !track.get(lastKey).outside) {
const interpolated = countInterpolatedFrames(lastKey, this.stopFrame, false);
labels[label].interpolated += interpolated;
labels[label].total += interpolated;
}
};
for (const object of Object.values(this.objects)) {
if (object.removed) {
continue;
}
let objectType = null;
if (object instanceof Shape) {
objectType = 'shape';
} else if (object instanceof Track) {
objectType = 'track';
} else if (object instanceof Tag) {
objectType = 'tag';
} else {
throw new ScriptingError(`Unexpected object type: "${objectType}"`);
}
const { name: label } = object.label;
if (objectType === 'tag' && !this.injection.framesInfo.isFrameDeleted(object.frame)) {
labels[label].tag++;
labels[label].manually++;
labels[label].total++;
} else if (objectType === 'track') {
scanTrack(object);