/
cvat.py
7877 lines (6537 loc) · 254 KB
/
cvat.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
"""
Utilities for working with datasets in
`CVAT format <https://github.com/opencv/cvat>`_.
| Copyright 2017-2024, Voxel51, Inc.
| `voxel51.com <https://voxel51.com/>`_
|
"""
from collections import defaultdict
from copy import copy, deepcopy
from datetime import datetime
import itertools
import logging
import math
import multiprocessing.dummy
import os
from packaging.version import Version
import time
import warnings
import webbrowser
from bson import ObjectId
import jinja2
import numpy as np
import requests
import urllib3
import eta.core.data as etad
import eta.core.image as etai
import eta.core.serial as etas
import eta.core.utils as etau
import fiftyone.constants as foc
import fiftyone.core.fields as fof
import fiftyone.core.labels as fol
import fiftyone.core.media as fom
import fiftyone.core.metadata as fomt
from fiftyone.core.sample import Sample
import fiftyone.core.storage as fos
import fiftyone.core.utils as fou
import fiftyone.utils.annotations as foua
import fiftyone.utils.data as foud
import fiftyone.utils.video as fouv
logger = logging.getLogger(__name__)
def import_annotations(
sample_collection,
project_name=None,
project_id=None,
task_ids=None,
data_path=None,
label_types=None,
insert_new=True,
download_media=False,
num_workers=None,
occluded_attr=None,
group_id_attr=None,
backend="cvat",
**kwargs,
):
"""Imports annotations from the specified CVAT project or task(s) into the
given sample collection.
Provide one of ``project_name``, ``project_id``, or ``task_ids`` to perform
an import.
This method can be configured in any of the following three ways:
1. Pass the ``data_path`` argument to define a mapping between media
filenames in CVAT and local filepaths to the same media.
2. Pass the ``download_media=True`` option to download both the
annotations and the media files themselves, which are stored in a
directory you specify via the ``data_path`` argument.
3. Don't provide ``data_path`` or ``download_media=True``, in which case
it is assumed that the CVAT filenames correspond to the base filenames
of existing sample filepaths in the provided ``sample_collection``.
Args:
sample_collection: a
:class:`fiftyone.core.collections.SampleCollection`
project_name (None): the name of a CVAT project to import
project_id (None): the ID of a CVAT project to import
task_ids (None): a CVAT task ID or iterable of CVAT task IDs to import
data_path (None): a parameter that defines the correspondence between
the filenames in CVAT and the filepaths of ``sample_collection``.
Can be any of the following:
- a directory on disk where the media files reside. In this case,
the filenames must match those in CVAT
- a dict mapping CVAT filenames to absolute filepaths to the
corresponding media on disk
- the path to a JSON manifest on disk containing a mapping
between CVAT filenames and absolute filepaths to the media on
disk
By default, only annotations whose filename matches an existing
filepath in ``sample_collection`` will be imported
label_types (None): an optional parameter specifying the label types to
import. Can be any of the following:
- ``None`` (default): all label types will be stored in fields of
the same name on ``sample_collection``
- a list of label types to load. In this case, the labels will be
stored in fields of the same names in ``sample_collection``
- a dict mapping label types to field names of
``sample_collection`` in which to store the labels
- ``"prompt"``: present an interactive prompt to decide/discard
field names in which to store each label type
insert_new (True): whether to create new samples for any media for
which annotations are found in CVAT but which do not exist in
``sample_collection``
download_media (False): whether to download the images or videos found
in CVAT to the directory or filepaths in ``data_path`` if not
already present
num_workers (None): a suggested number of threads to use when
downloading media
occluded_attr (None): an optional attribute name in which to store the
occlusion information for all spatial labels
group_id_attr (None): an optional attribute name in which to store the
group id for labels
backend ("cvat"): the name of the CVAT backend to use
**kwargs: CVAT authentication credentials to pass to
:class:`CVATBackendConfig`
"""
if sample_collection.media_type == fom.GROUP:
if insert_new:
raise ValueError(
"insert_new=True is not supported for grouped collections"
)
sample_collection = sample_collection.select_group_slices(
_allow_mixed=True
)
if bool(project_name) + bool(project_id) + bool(task_ids) != 1:
raise ValueError(
"Exactly one of 'project_name', 'project_id', or 'task_ids' must "
"be provided"
)
config = foua._parse_config(
backend,
None,
occluded_attr=occluded_attr,
group_id_attr=group_id_attr,
**kwargs,
)
anno_backend = config.build()
api = anno_backend.connect_to_api()
if project_name is not None:
project_id = api.get_project_id(project_name)
if project_id is not None:
task_ids = api.get_project_tasks(project_id)
if etau.is_str(task_ids):
task_ids = [task_ids]
else:
task_ids = list(task_ids)
# Build mapping from CVAT filenames to local filepaths
data_dir = None
existing_filepaths = sample_collection.values("filepath")
if data_path is None:
data_map = {os.path.basename(f): f for f in existing_filepaths}
elif etau.is_str(data_path) and data_path.endswith(".json"):
data_map = etas.read_json(data_path)
elif etau.is_str(data_path):
if os.path.isdir(data_path):
data_map = {
os.path.basename(f): f
for f in etau.list_files(
data_path, abs_paths=True, recursive=True
)
}
else:
data_map = {}
data_dir = data_path
else:
data_map = data_path
# Determine what filepaths we have annotations for
cvat_id_map = {}
task_filepaths = []
ignored_filenames = []
download_tasks = []
for task_id in task_ids:
cvat_id_map[task_id] = _parse_task_metadata(
api,
task_id,
data_map,
task_filepaths,
ignored_filenames,
download_tasks,
data_dir=data_dir,
download_media=download_media,
)
# Download media from CVAT, if requested
if download_tasks:
_download_media(download_tasks, num_workers)
if ignored_filenames:
logger.warning(
"Ignoring annotations for %d files in CVAT (eg %s) that do not "
"appear in the provided data map",
len(ignored_filenames),
ignored_filenames[0],
)
if not task_filepaths:
logger.warning("No applicable annotations found to download")
return
dataset = sample_collection._dataset
new_filepaths = set(task_filepaths) - set(existing_filepaths)
# Insert samples for new filepaths, if necessary and we're allowed to
if new_filepaths:
if insert_new:
dataset.add_samples([Sample(filepath=fp) for fp in new_filepaths])
else:
logger.warning(
"Ignoring annotations for %d filepaths (eg %s) that do not "
"appear in the input collection",
len(new_filepaths),
next(iter(new_filepaths)),
)
if dataset.media_type == fom.VIDEO:
# The download implementation requires IDs for all possible frames
dataset.select_by("filepath", task_filepaths).ensure_frames()
anno_key = "tmp_" + str(ObjectId())
anno_backend.register_run(dataset, anno_key, overwrite=False)
# Download annotations
try:
if project_id is not None:
# CVAT projects share a label schema, so we can download all tasks
# in one batch
label_schema = api._get_label_schema(
project_id=project_id,
occluded_attr=occluded_attr,
group_id_attr=group_id_attr,
)
_download_annotations(
dataset,
task_ids,
cvat_id_map,
label_schema,
label_types,
anno_backend,
anno_key,
**kwargs,
)
else:
# Each task may have a different label schema, so we must download
# each task separately
for task_id in task_ids:
label_schema = api._get_label_schema(
task_id=task_id,
occluded_attr=occluded_attr,
group_id_attr=group_id_attr,
)
_download_annotations(
dataset,
[task_id],
cvat_id_map,
label_schema,
label_types,
anno_backend,
anno_key,
**kwargs,
)
finally:
anno_backend.delete_run(dataset, anno_key)
api.close()
def _parse_task_metadata(
api,
task_id,
data_map,
task_filepaths,
ignored_filenames,
download_tasks,
data_dir=None,
download_media=False,
):
resp = api.get(api.task_data_meta_url(task_id)).json()
start_frame = resp.get("start_frame", None)
stop_frame = resp.get("stop_frame", None)
chunk_size = resp.get("chunk_size", None)
cvat_id_map = {}
for frame_id, frame in enumerate(resp["frames"]):
filename = frame["name"]
filepath = data_map.get(filename, None)
if download_media:
if filepath is None and data_dir:
filepath = os.path.join(data_dir, filename)
if filepath and not os.path.exists(filepath):
download_tasks.append(
(
api,
task_id,
frame_id,
filepath,
start_frame,
stop_frame,
chunk_size,
)
)
if filepath is not None:
cvat_id_map[filepath] = frame_id
task_filepaths.append(filepath)
else:
ignored_filenames.append(filename)
return cvat_id_map
def _download_media(tasks, num_workers):
num_workers = fou.recommend_thread_pool_workers(num_workers)
logger.info("Downloading media...")
if num_workers <= 1:
with fou.ProgressBar() as pb:
for task in pb(tasks):
_do_download_media(task)
else:
with multiprocessing.dummy.Pool(processes=num_workers) as pool:
with fou.ProgressBar(total=len(tasks)) as pb:
for _ in pb(pool.imap_unordered(_do_download_media, tasks)):
pass
def _do_download_media(task):
(
api,
task_id,
frame_id,
filepath,
start_frame,
stop_frame,
chunk_size,
) = task
if fom.get_media_type(filepath) == fom.VIDEO:
ext = os.path.splitext(filepath)[1]
num_chunks = int(np.ceil((stop_frame - start_frame) / chunk_size))
# CVAT stores videos in chunks, so we must download them individually
# and then concatenate them...
with etau.TempDir() as tmp_dir:
chunk_paths = []
for chunk_id in range(num_chunks):
resp = api.get(
api.task_data_download_url(
task_id, chunk_id, data_type="chunk"
)
)
chunk_path = os.path.join(tmp_dir, "%d.%s" % (chunk_id, ext))
etau.write_file(resp._content, chunk_path)
chunk_paths.append(chunk_path)
fouv.concat_videos(chunk_paths, filepath)
else:
resp = api.get(api.task_data_download_url(task_id, frame_id))
etau.write_file(resp._content, filepath)
def _download_annotations(
dataset,
task_ids,
cvat_id_map,
label_schema,
label_types,
anno_backend,
anno_key,
**kwargs,
):
config = anno_backend.config
config.label_schema = label_schema
anno_backend.update_run_config(dataset, anno_key, config)
id_map = {}
server_id_map = {}
project_ids = []
job_ids = []
frame_id_map = {
task_id: _build_sparse_frame_id_map(dataset, cvat_id_map[task_id])
for task_id in task_ids
}
labels_task_map = {None: task_ids}
results = CVATAnnotationResults(
dataset,
config,
anno_key,
id_map,
server_id_map,
project_ids,
task_ids,
job_ids,
frame_id_map,
labels_task_map,
backend=anno_backend,
)
anno_backend.save_run_results(dataset, anno_key, results)
if label_types is None:
unexpected = "keep"
else:
unexpected = label_types
dataset.load_annotations(
anno_key, unexpected=unexpected, cleanup=False, **kwargs
)
def _build_sparse_frame_id_map(dataset, cvat_id_map):
task_filepaths = list(cvat_id_map.keys())
samples = dataset.select_by("filepath", task_filepaths)
frame_id_map = {}
if samples.media_type == fom.VIDEO:
# Video tasks have exactly one video, and we download labels for all
# of its frames
frame_id = -1
sample_ids, frame_ids = samples.values(["id", "frames.id"])
for sample_id, _frame_ids in zip(sample_ids, frame_ids):
for _frame_id in _frame_ids:
frame_id += 1
frame_id_map[frame_id] = {
"sample_id": sample_id,
"frame_id": _frame_id,
}
else:
# For image tasks, only allow downloads for filepaths in `cvat_id_map`
sample_ids, filepaths = samples.values(["id", "filepath"])
for sample_id, filepath in zip(sample_ids, filepaths):
frame_id = cvat_id_map.get(filepath, None)
if frame_id is not None:
frame_id_map[frame_id] = {"sample_id": sample_id}
return frame_id_map
class CVATImageDatasetImporter(
foud.LabeledImageDatasetImporter, foud.ImportPathsMixin
):
"""Importer for CVAT image datasets stored on disk.
See :ref:`this page <CVATImageDataset-import>` for format details.
Args:
dataset_dir (None): the dataset directory. If omitted, ``data_path``
and/or ``labels_path`` must be provided
data_path (None): an optional parameter that enables explicit control
over the location of the media. Can be any of the following:
- a folder name like ``"data"`` or ``"data/"`` specifying a
subfolder of ``dataset_dir`` where the media files reside
- an absolute directory path where the media files reside. In
this case, the ``dataset_dir`` has no effect on the location of
the data
- a filename like ``"data.json"`` specifying the filename of the
JSON data manifest file in ``dataset_dir``
- an absolute filepath specifying the location of the JSON data
manifest. In this case, ``dataset_dir`` has no effect on the
location of the data
- a dict mapping filenames to absolute filepaths
If None, this parameter will default to whichever of ``data/`` or
``data.json`` exists in the dataset directory
labels_path (None): an optional parameter that enables explicit control
over the location of the labels. Can be any of the following:
- a filename like ``"labels.xml"`` specifying the location of the
labels in ``dataset_dir``
- an absolute filepath to the labels. In this case,
``dataset_dir`` has no effect on the location of the labels
If None, the parameter will default to ``labels.xml``
include_all_data (False): whether to generate samples for all images in
the data directory (True) rather than only creating samples for
images with label entries (False)
shuffle (False): whether to randomly shuffle the order in which the
samples are imported
seed (None): a random seed to use when shuffling
max_samples (None): a maximum number of samples to import. By default,
all samples are imported
"""
def __init__(
self,
dataset_dir=None,
data_path=None,
labels_path=None,
include_all_data=False,
shuffle=False,
seed=None,
max_samples=None,
):
if dataset_dir is None and data_path is None and labels_path is None:
raise ValueError(
"At least one of `dataset_dir`, `data_path`, and "
"`labels_path` must be provided"
)
data_path = self._parse_data_path(
dataset_dir=dataset_dir,
data_path=data_path,
default="data/",
)
labels_path = self._parse_labels_path(
dataset_dir=dataset_dir,
labels_path=labels_path,
default="labels.xml",
)
super().__init__(
dataset_dir=dataset_dir,
shuffle=shuffle,
seed=seed,
max_samples=max_samples,
)
self.data_path = data_path
self.labels_path = labels_path
self.include_all_data = include_all_data
self._info = None
self._image_paths_map = None
self._cvat_images_map = None
self._filenames = None
self._iter_filenames = None
self._num_samples = None
def __iter__(self):
self._iter_filenames = iter(self._filenames)
return self
def __len__(self):
return self._num_samples
def __next__(self):
filename = next(self._iter_filenames)
if os.path.isabs(filename):
image_path = filename
else:
image_path = self._image_paths_map[filename]
cvat_image = self._cvat_images_map.get(filename, None)
if cvat_image is not None:
# Labeled image
image_metadata = cvat_image.get_image_metadata()
labels = cvat_image.to_labels()
else:
# Unlabeled image
image_metadata = None
labels = None
return image_path, image_metadata, labels
@property
def has_dataset_info(self):
return True
@property
def has_image_metadata(self):
return True
@property
def label_cls(self):
return {
"classifications": fol.Classifications,
"detections": fol.Detections,
"polylines": fol.Polylines,
"keypoints": fol.Keypoints,
}
def setup(self):
image_paths_map = self._load_data_map(self.data_path, recursive=True)
if self.labels_path is not None and os.path.isfile(self.labels_path):
info, _, cvat_images = load_cvat_image_annotations(
self.labels_path
)
else:
info = {}
cvat_images = []
self._info = info
# Use subset/name as the key if it exists, else just name
cvat_images_map = {}
for i in cvat_images:
if i.subset:
key = os.path.join(i.subset, i.name)
else:
key = i.name
cvat_images_map[fos.normpath(key)] = i
filenames = set(cvat_images_map.keys())
if self.include_all_data:
filenames.update(image_paths_map.keys())
filenames = self._preprocess_list(sorted(filenames))
self._image_paths_map = image_paths_map
self._cvat_images_map = cvat_images_map
self._filenames = filenames
self._num_samples = len(filenames)
def get_dataset_info(self):
return self._info
class CVATVideoDatasetImporter(
foud.LabeledVideoDatasetImporter, foud.ImportPathsMixin
):
"""Importer for CVAT video datasets stored on disk.
See :ref:`this page <CVATVideoDataset-import>` for format details.
Args:
dataset_dir (None): the dataset directory. If omitted, ``data_path``
and/or ``labels_path`` must be provided
data_path (None): an optional parameter that enables explicit control
over the location of the media. Can be any of the following:
- a folder name like ``"data"`` or ``"data/"`` specifying a
subfolder of ``dataset_dir`` where the media files reside
- an absolute directory path where the media files reside. In
this case, the ``dataset_dir`` has no effect on the location of
the data
- a filename like ``"data.json"`` specifying the filename of the
JSON data manifest file in ``dataset_dir``
- an absolute filepath specifying the location of the JSON data
manifest. In this case, ``dataset_dir`` has no effect on the
location of the data
- a dict mapping filenames to absolute filepaths
If None, this parameter will default to whichever of ``data/`` or
``data.json`` exists in the dataset directory
labels_path (None): an optional parameter that enables explicit control
over the location of the labels. Can be any of the following:
- a folder name like ``"labels"`` or ``"labels/"`` specifying the
location of the labels in ``dataset_dir``
- an absolute folder path to the labels. In this case,
``dataset_dir`` has no effect on the location of the labels
If None, the parameter will default to ``labels/``
include_all_data (False): whether to generate samples for all videos in
the data directory (True) rather than only creating samples for
videos with label entries (False)
shuffle (False): whether to randomly shuffle the order in which the
samples are imported
seed (None): a random seed to use when shuffling
max_samples (None): a maximum number of samples to import. By default,
all samples are imported
"""
def __init__(
self,
dataset_dir=None,
data_path=None,
labels_path=None,
include_all_data=False,
shuffle=False,
seed=None,
max_samples=None,
):
if dataset_dir is None and data_path is None and labels_path is None:
raise ValueError(
"At least one of `dataset_dir`, `data_path`, and "
"`labels_path` must be provided"
)
data_path = self._parse_data_path(
dataset_dir=dataset_dir,
data_path=data_path,
default="data/",
)
labels_path = self._parse_labels_path(
dataset_dir=dataset_dir,
labels_path=labels_path,
default="labels/",
)
super().__init__(
dataset_dir=dataset_dir,
shuffle=shuffle,
seed=seed,
max_samples=max_samples,
)
self.data_path = data_path
self.labels_path = labels_path
self.include_all_data = include_all_data
self._info = None
self._cvat_task_labels = None
self._video_paths_map = None
self._labels_paths_map = None
self._uuids = None
self._iter_uuids = None
self._num_samples = None
def __iter__(self):
self._iter_uuids = iter(self._uuids)
return self
def __len__(self):
return self._num_samples
def __next__(self):
uuid = next(self._iter_uuids)
video_path = self._video_paths_map[uuid]
labels_path = self._labels_paths_map.get(uuid, None)
if labels_path:
# Labeled video
info, cvat_task_labels, cvat_tracks = load_cvat_video_annotations(
labels_path
)
if self._info is None:
self._info = info
self._cvat_task_labels.merge_task_labels(cvat_task_labels)
self._info["task_labels"] = self._cvat_task_labels.labels
frames = _cvat_tracks_to_frames_dict(cvat_tracks)
else:
# Unlabeled video
frames = None
return video_path, None, None, frames
@property
def has_dataset_info(self):
return True
@property
def has_video_metadata(self):
return False # has (width, height) but not other important info
@property
def label_cls(self):
return None
@property
def frame_labels_cls(self):
return {
"detections": fol.Detections,
"polylines": fol.Polylines,
"keypoints": fol.Keypoints,
}
def setup(self):
video_paths_map = self._load_data_map(
self.data_path, ignore_exts=True, recursive=True
)
if self.labels_path is not None and os.path.isdir(self.labels_path):
labels_path = fos.normpath(self.labels_path)
labels_paths_map = {
os.path.splitext(p)[0]: os.path.join(labels_path, p)
for p in etau.list_files(labels_path, recursive=True)
if etau.has_extension(p, ".xml")
}
else:
labels_paths_map = {}
uuids = set(labels_paths_map.keys())
if self.include_all_data:
uuids.update(video_paths_map.keys())
uuids = self._preprocess_list(sorted(uuids))
self._cvat_task_labels = CVATTaskLabels()
self._video_paths_map = video_paths_map
self._labels_paths_map = labels_paths_map
self._uuids = uuids
self._num_samples = len(uuids)
def get_dataset_info(self):
return self._info
class CVATImageDatasetExporter(
foud.LabeledImageDatasetExporter, foud.ExportPathsMixin
):
"""Exporter that writes CVAT image datasets to disk.
See :ref:`this page <CVATImageDataset-export>` for format details.
Args:
export_dir (None): the directory to write the export. This has no
effect if ``data_path`` and ``labels_path`` are absolute paths
data_path (None): an optional parameter that enables explicit control
over the location of the exported media. Can be any of the
following:
- a folder name like ``"data"`` or ``"data/"`` specifying a
subfolder of ``export_dir`` in which to export the media
- an absolute directory path in which to export the media. In
this case, the ``export_dir`` has no effect on the location of
the data
- a JSON filename like ``"data.json"`` specifying the filename of
the manifest file in ``export_dir`` generated when
``export_media`` is ``"manifest"``
- an absolute filepath specifying the location to write the JSON
manifest file when ``export_media`` is ``"manifest"``. In this
case, ``export_dir`` has no effect on the location of the data
If None, the default value of this parameter will be chosen based
on the value of the ``export_media`` parameter
labels_path (None): an optional parameter that enables explicit control
over the location of the exported labels. Can be any of the
following:
- a filename like ``"labels.xml"`` specifying the location in
``export_dir`` in which to export the labels
- an absolute filepath to which to export the labels. In this
case, the ``export_dir`` has no effect on the location of the
labels
If None, the labels will be exported into ``export_dir`` using the
default filename
export_media (None): controls how to export the raw media. The
supported values are:
- ``True``: copy all media files into the output directory
- ``False``: don't export media
- ``"move"``: move all media files into the output directory
- ``"symlink"``: create symlinks to the media files in the output
directory
- ``"manifest"``: create a ``data.json`` in the output directory
that maps UUIDs used in the labels files to the filepaths of
the source media, rather than exporting the actual media
If None, the default value of this parameter will be chosen based
on the value of the ``data_path`` parameter
rel_dir (None): an optional relative directory to strip from each input
filepath to generate a unique identifier for each image. When
exporting media, this identifier is joined with ``data_path`` to
generate an output path for each exported image. This argument
allows for populating nested subdirectories that match the shape of
the input paths. The path is converted to an absolute path (if
necessary) via :func:`fiftyone.core.storage.normalize_path`
abs_paths (False): whether to store absolute paths to the images in the
exported labels
image_format (None): the image format to use when writing in-memory
images to disk. By default, ``fiftyone.config.default_image_ext``
is used
"""
def __init__(
self,
export_dir=None,
data_path=None,
labels_path=None,
export_media=None,
rel_dir=None,
abs_paths=False,
image_format=None,
):
data_path, export_media = self._parse_data_path(
export_dir=export_dir,
data_path=data_path,
export_media=export_media,
default="data/",
)
labels_path = self._parse_labels_path(
export_dir=export_dir,
labels_path=labels_path,
default="labels.xml",
)
super().__init__(export_dir=export_dir)
self.data_path = data_path
self.labels_path = labels_path
self.export_media = export_media
self.rel_dir = rel_dir
self.abs_paths = abs_paths
self.image_format = image_format
self._name = None
self._task_labels = None
self._cvat_images = None
self._media_exporter = None
@property
def requires_image_metadata(self):
return True
@property
def label_cls(self):
return {
"classifications": fol.Classifications,
"detections": fol.Detections,
"polylines": fol.Polylines,
"keypoints": fol.Keypoints,
}
def setup(self):
self._cvat_images = []
self._media_exporter = foud.ImageExporter(
self.export_media,
export_path=self.data_path,
rel_dir=self.rel_dir,
default_ext=self.image_format,
)
self._media_exporter.setup()
def log_collection(self, sample_collection):
self._name = sample_collection._dataset.name
self._task_labels = sample_collection.info.get("task_labels", None)
def export_sample(self, image_or_path, labels, metadata=None):
out_image_path, uuid = self._media_exporter.export(image_or_path)
if labels is None:
return # unlabeled
if not isinstance(labels, dict):
labels = {"labels": labels}
if all(v is None for v in labels.values()):
return # unlabeled
if metadata is None:
metadata = fomt.ImageMetadata.build_for(image_or_path)
if self.abs_paths:
name = out_image_path
else:
name = uuid
cvat_image = CVATImage.from_labels(labels, metadata)
cvat_image.id = len(self._cvat_images)
cvat_image.name = name
self._cvat_images.append(cvat_image)
def close(self, *args):
# Get task labels
if self._task_labels is None:
# Compute task labels from active label schema
cvat_task_labels = CVATTaskLabels.from_cvat_images(
self._cvat_images
)
else:
# Use task labels from logged collection info
cvat_task_labels = CVATTaskLabels(labels=self._task_labels)
# Write annotations
writer = CVATImageAnnotationWriter()
writer.write(
cvat_task_labels,
self._cvat_images,
self.labels_path,
id=0,
name=self._name,
)
self._media_exporter.close()
class CVATVideoDatasetExporter(
foud.LabeledVideoDatasetExporter, foud.ExportPathsMixin