dgenerate-ultralytics-headless 8.3.134__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- dgenerate_ultralytics_headless-8.3.134.dist-info/METADATA +400 -0
- dgenerate_ultralytics_headless-8.3.134.dist-info/RECORD +272 -0
- dgenerate_ultralytics_headless-8.3.134.dist-info/WHEEL +5 -0
- dgenerate_ultralytics_headless-8.3.134.dist-info/entry_points.txt +3 -0
- dgenerate_ultralytics_headless-8.3.134.dist-info/licenses/LICENSE +661 -0
- dgenerate_ultralytics_headless-8.3.134.dist-info/top_level.txt +1 -0
- tests/__init__.py +22 -0
- tests/conftest.py +83 -0
- tests/test_cli.py +138 -0
- tests/test_cuda.py +215 -0
- tests/test_engine.py +131 -0
- tests/test_exports.py +236 -0
- tests/test_integrations.py +154 -0
- tests/test_python.py +694 -0
- tests/test_solutions.py +187 -0
- ultralytics/__init__.py +30 -0
- ultralytics/assets/bus.jpg +0 -0
- ultralytics/assets/zidane.jpg +0 -0
- ultralytics/cfg/__init__.py +1023 -0
- ultralytics/cfg/datasets/Argoverse.yaml +77 -0
- ultralytics/cfg/datasets/DOTAv1.5.yaml +37 -0
- ultralytics/cfg/datasets/DOTAv1.yaml +36 -0
- ultralytics/cfg/datasets/GlobalWheat2020.yaml +68 -0
- ultralytics/cfg/datasets/HomeObjects-3K.yaml +33 -0
- ultralytics/cfg/datasets/ImageNet.yaml +2025 -0
- ultralytics/cfg/datasets/Objects365.yaml +443 -0
- ultralytics/cfg/datasets/SKU-110K.yaml +58 -0
- ultralytics/cfg/datasets/VOC.yaml +106 -0
- ultralytics/cfg/datasets/VisDrone.yaml +77 -0
- ultralytics/cfg/datasets/african-wildlife.yaml +25 -0
- ultralytics/cfg/datasets/brain-tumor.yaml +23 -0
- ultralytics/cfg/datasets/carparts-seg.yaml +44 -0
- ultralytics/cfg/datasets/coco-pose.yaml +42 -0
- ultralytics/cfg/datasets/coco.yaml +118 -0
- ultralytics/cfg/datasets/coco128-seg.yaml +101 -0
- ultralytics/cfg/datasets/coco128.yaml +101 -0
- ultralytics/cfg/datasets/coco8-multispectral.yaml +104 -0
- ultralytics/cfg/datasets/coco8-pose.yaml +26 -0
- ultralytics/cfg/datasets/coco8-seg.yaml +101 -0
- ultralytics/cfg/datasets/coco8.yaml +101 -0
- ultralytics/cfg/datasets/crack-seg.yaml +22 -0
- ultralytics/cfg/datasets/dog-pose.yaml +24 -0
- ultralytics/cfg/datasets/dota8-multispectral.yaml +38 -0
- ultralytics/cfg/datasets/dota8.yaml +35 -0
- ultralytics/cfg/datasets/hand-keypoints.yaml +26 -0
- ultralytics/cfg/datasets/lvis.yaml +1240 -0
- ultralytics/cfg/datasets/medical-pills.yaml +22 -0
- ultralytics/cfg/datasets/open-images-v7.yaml +666 -0
- ultralytics/cfg/datasets/package-seg.yaml +22 -0
- ultralytics/cfg/datasets/signature.yaml +21 -0
- ultralytics/cfg/datasets/tiger-pose.yaml +25 -0
- ultralytics/cfg/datasets/xView.yaml +155 -0
- ultralytics/cfg/default.yaml +127 -0
- ultralytics/cfg/models/11/yolo11-cls-resnet18.yaml +17 -0
- ultralytics/cfg/models/11/yolo11-cls.yaml +33 -0
- ultralytics/cfg/models/11/yolo11-obb.yaml +50 -0
- ultralytics/cfg/models/11/yolo11-pose.yaml +51 -0
- ultralytics/cfg/models/11/yolo11-seg.yaml +50 -0
- ultralytics/cfg/models/11/yolo11.yaml +50 -0
- ultralytics/cfg/models/11/yoloe-11-seg.yaml +48 -0
- ultralytics/cfg/models/11/yoloe-11.yaml +48 -0
- ultralytics/cfg/models/12/yolo12-cls.yaml +32 -0
- ultralytics/cfg/models/12/yolo12-obb.yaml +48 -0
- ultralytics/cfg/models/12/yolo12-pose.yaml +49 -0
- ultralytics/cfg/models/12/yolo12-seg.yaml +48 -0
- ultralytics/cfg/models/12/yolo12.yaml +48 -0
- ultralytics/cfg/models/rt-detr/rtdetr-l.yaml +53 -0
- ultralytics/cfg/models/rt-detr/rtdetr-resnet101.yaml +45 -0
- ultralytics/cfg/models/rt-detr/rtdetr-resnet50.yaml +45 -0
- ultralytics/cfg/models/rt-detr/rtdetr-x.yaml +57 -0
- ultralytics/cfg/models/v10/yolov10b.yaml +45 -0
- ultralytics/cfg/models/v10/yolov10l.yaml +45 -0
- ultralytics/cfg/models/v10/yolov10m.yaml +45 -0
- ultralytics/cfg/models/v10/yolov10n.yaml +45 -0
- ultralytics/cfg/models/v10/yolov10s.yaml +45 -0
- ultralytics/cfg/models/v10/yolov10x.yaml +45 -0
- ultralytics/cfg/models/v3/yolov3-spp.yaml +49 -0
- ultralytics/cfg/models/v3/yolov3-tiny.yaml +40 -0
- ultralytics/cfg/models/v3/yolov3.yaml +49 -0
- ultralytics/cfg/models/v5/yolov5-p6.yaml +62 -0
- ultralytics/cfg/models/v5/yolov5.yaml +51 -0
- ultralytics/cfg/models/v6/yolov6.yaml +56 -0
- ultralytics/cfg/models/v8/yoloe-v8-seg.yaml +45 -0
- ultralytics/cfg/models/v8/yoloe-v8.yaml +45 -0
- ultralytics/cfg/models/v8/yolov8-cls-resnet101.yaml +28 -0
- ultralytics/cfg/models/v8/yolov8-cls-resnet50.yaml +28 -0
- ultralytics/cfg/models/v8/yolov8-cls.yaml +32 -0
- ultralytics/cfg/models/v8/yolov8-ghost-p2.yaml +58 -0
- ultralytics/cfg/models/v8/yolov8-ghost-p6.yaml +60 -0
- ultralytics/cfg/models/v8/yolov8-ghost.yaml +50 -0
- ultralytics/cfg/models/v8/yolov8-obb.yaml +49 -0
- ultralytics/cfg/models/v8/yolov8-p2.yaml +57 -0
- ultralytics/cfg/models/v8/yolov8-p6.yaml +59 -0
- ultralytics/cfg/models/v8/yolov8-pose-p6.yaml +60 -0
- ultralytics/cfg/models/v8/yolov8-pose.yaml +50 -0
- ultralytics/cfg/models/v8/yolov8-rtdetr.yaml +49 -0
- ultralytics/cfg/models/v8/yolov8-seg-p6.yaml +59 -0
- ultralytics/cfg/models/v8/yolov8-seg.yaml +49 -0
- ultralytics/cfg/models/v8/yolov8-world.yaml +51 -0
- ultralytics/cfg/models/v8/yolov8-worldv2.yaml +49 -0
- ultralytics/cfg/models/v8/yolov8.yaml +49 -0
- ultralytics/cfg/models/v9/yolov9c-seg.yaml +41 -0
- ultralytics/cfg/models/v9/yolov9c.yaml +41 -0
- ultralytics/cfg/models/v9/yolov9e-seg.yaml +64 -0
- ultralytics/cfg/models/v9/yolov9e.yaml +64 -0
- ultralytics/cfg/models/v9/yolov9m.yaml +41 -0
- ultralytics/cfg/models/v9/yolov9s.yaml +41 -0
- ultralytics/cfg/models/v9/yolov9t.yaml +41 -0
- ultralytics/cfg/trackers/botsort.yaml +22 -0
- ultralytics/cfg/trackers/bytetrack.yaml +14 -0
- ultralytics/data/__init__.py +26 -0
- ultralytics/data/annotator.py +66 -0
- ultralytics/data/augment.py +2945 -0
- ultralytics/data/base.py +438 -0
- ultralytics/data/build.py +258 -0
- ultralytics/data/converter.py +754 -0
- ultralytics/data/dataset.py +834 -0
- ultralytics/data/loaders.py +676 -0
- ultralytics/data/scripts/download_weights.sh +18 -0
- ultralytics/data/scripts/get_coco.sh +61 -0
- ultralytics/data/scripts/get_coco128.sh +18 -0
- ultralytics/data/scripts/get_imagenet.sh +52 -0
- ultralytics/data/split.py +125 -0
- ultralytics/data/split_dota.py +325 -0
- ultralytics/data/utils.py +777 -0
- ultralytics/engine/__init__.py +1 -0
- ultralytics/engine/exporter.py +1519 -0
- ultralytics/engine/model.py +1156 -0
- ultralytics/engine/predictor.py +502 -0
- ultralytics/engine/results.py +1840 -0
- ultralytics/engine/trainer.py +853 -0
- ultralytics/engine/tuner.py +243 -0
- ultralytics/engine/validator.py +377 -0
- ultralytics/hub/__init__.py +168 -0
- ultralytics/hub/auth.py +137 -0
- ultralytics/hub/google/__init__.py +176 -0
- ultralytics/hub/session.py +446 -0
- ultralytics/hub/utils.py +248 -0
- ultralytics/models/__init__.py +9 -0
- ultralytics/models/fastsam/__init__.py +7 -0
- ultralytics/models/fastsam/model.py +61 -0
- ultralytics/models/fastsam/predict.py +181 -0
- ultralytics/models/fastsam/utils.py +24 -0
- ultralytics/models/fastsam/val.py +40 -0
- ultralytics/models/nas/__init__.py +7 -0
- ultralytics/models/nas/model.py +102 -0
- ultralytics/models/nas/predict.py +58 -0
- ultralytics/models/nas/val.py +39 -0
- ultralytics/models/rtdetr/__init__.py +7 -0
- ultralytics/models/rtdetr/model.py +63 -0
- ultralytics/models/rtdetr/predict.py +84 -0
- ultralytics/models/rtdetr/train.py +85 -0
- ultralytics/models/rtdetr/val.py +191 -0
- ultralytics/models/sam/__init__.py +6 -0
- ultralytics/models/sam/amg.py +260 -0
- ultralytics/models/sam/build.py +358 -0
- ultralytics/models/sam/model.py +170 -0
- ultralytics/models/sam/modules/__init__.py +1 -0
- ultralytics/models/sam/modules/blocks.py +1129 -0
- ultralytics/models/sam/modules/decoders.py +515 -0
- ultralytics/models/sam/modules/encoders.py +854 -0
- ultralytics/models/sam/modules/memory_attention.py +299 -0
- ultralytics/models/sam/modules/sam.py +1006 -0
- ultralytics/models/sam/modules/tiny_encoder.py +1002 -0
- ultralytics/models/sam/modules/transformer.py +351 -0
- ultralytics/models/sam/modules/utils.py +394 -0
- ultralytics/models/sam/predict.py +1605 -0
- ultralytics/models/utils/__init__.py +1 -0
- ultralytics/models/utils/loss.py +455 -0
- ultralytics/models/utils/ops.py +268 -0
- ultralytics/models/yolo/__init__.py +7 -0
- ultralytics/models/yolo/classify/__init__.py +7 -0
- ultralytics/models/yolo/classify/predict.py +88 -0
- ultralytics/models/yolo/classify/train.py +233 -0
- ultralytics/models/yolo/classify/val.py +215 -0
- ultralytics/models/yolo/detect/__init__.py +7 -0
- ultralytics/models/yolo/detect/predict.py +124 -0
- ultralytics/models/yolo/detect/train.py +217 -0
- ultralytics/models/yolo/detect/val.py +451 -0
- ultralytics/models/yolo/model.py +354 -0
- ultralytics/models/yolo/obb/__init__.py +7 -0
- ultralytics/models/yolo/obb/predict.py +66 -0
- ultralytics/models/yolo/obb/train.py +81 -0
- ultralytics/models/yolo/obb/val.py +283 -0
- ultralytics/models/yolo/pose/__init__.py +7 -0
- ultralytics/models/yolo/pose/predict.py +79 -0
- ultralytics/models/yolo/pose/train.py +154 -0
- ultralytics/models/yolo/pose/val.py +394 -0
- ultralytics/models/yolo/segment/__init__.py +7 -0
- ultralytics/models/yolo/segment/predict.py +113 -0
- ultralytics/models/yolo/segment/train.py +123 -0
- ultralytics/models/yolo/segment/val.py +428 -0
- ultralytics/models/yolo/world/__init__.py +5 -0
- ultralytics/models/yolo/world/train.py +119 -0
- ultralytics/models/yolo/world/train_world.py +176 -0
- ultralytics/models/yolo/yoloe/__init__.py +22 -0
- ultralytics/models/yolo/yoloe/predict.py +169 -0
- ultralytics/models/yolo/yoloe/train.py +298 -0
- ultralytics/models/yolo/yoloe/train_seg.py +124 -0
- ultralytics/models/yolo/yoloe/val.py +191 -0
- ultralytics/nn/__init__.py +29 -0
- ultralytics/nn/autobackend.py +842 -0
- ultralytics/nn/modules/__init__.py +182 -0
- ultralytics/nn/modules/activation.py +53 -0
- ultralytics/nn/modules/block.py +1966 -0
- ultralytics/nn/modules/conv.py +712 -0
- ultralytics/nn/modules/head.py +880 -0
- ultralytics/nn/modules/transformer.py +713 -0
- ultralytics/nn/modules/utils.py +164 -0
- ultralytics/nn/tasks.py +1627 -0
- ultralytics/nn/text_model.py +351 -0
- ultralytics/solutions/__init__.py +41 -0
- ultralytics/solutions/ai_gym.py +116 -0
- ultralytics/solutions/analytics.py +252 -0
- ultralytics/solutions/config.py +106 -0
- ultralytics/solutions/distance_calculation.py +124 -0
- ultralytics/solutions/heatmap.py +127 -0
- ultralytics/solutions/instance_segmentation.py +84 -0
- ultralytics/solutions/object_blurrer.py +90 -0
- ultralytics/solutions/object_counter.py +195 -0
- ultralytics/solutions/object_cropper.py +84 -0
- ultralytics/solutions/parking_management.py +273 -0
- ultralytics/solutions/queue_management.py +93 -0
- ultralytics/solutions/region_counter.py +120 -0
- ultralytics/solutions/security_alarm.py +154 -0
- ultralytics/solutions/similarity_search.py +172 -0
- ultralytics/solutions/solutions.py +724 -0
- ultralytics/solutions/speed_estimation.py +110 -0
- ultralytics/solutions/streamlit_inference.py +196 -0
- ultralytics/solutions/templates/similarity-search.html +160 -0
- ultralytics/solutions/trackzone.py +88 -0
- ultralytics/solutions/vision_eye.py +68 -0
- ultralytics/trackers/__init__.py +7 -0
- ultralytics/trackers/basetrack.py +124 -0
- ultralytics/trackers/bot_sort.py +260 -0
- ultralytics/trackers/byte_tracker.py +480 -0
- ultralytics/trackers/track.py +125 -0
- ultralytics/trackers/utils/__init__.py +1 -0
- ultralytics/trackers/utils/gmc.py +376 -0
- ultralytics/trackers/utils/kalman_filter.py +493 -0
- ultralytics/trackers/utils/matching.py +157 -0
- ultralytics/utils/__init__.py +1435 -0
- ultralytics/utils/autobatch.py +106 -0
- ultralytics/utils/autodevice.py +174 -0
- ultralytics/utils/benchmarks.py +695 -0
- ultralytics/utils/callbacks/__init__.py +5 -0
- ultralytics/utils/callbacks/base.py +234 -0
- ultralytics/utils/callbacks/clearml.py +153 -0
- ultralytics/utils/callbacks/comet.py +552 -0
- ultralytics/utils/callbacks/dvc.py +205 -0
- ultralytics/utils/callbacks/hub.py +108 -0
- ultralytics/utils/callbacks/mlflow.py +138 -0
- ultralytics/utils/callbacks/neptune.py +140 -0
- ultralytics/utils/callbacks/raytune.py +43 -0
- ultralytics/utils/callbacks/tensorboard.py +132 -0
- ultralytics/utils/callbacks/wb.py +185 -0
- ultralytics/utils/checks.py +897 -0
- ultralytics/utils/dist.py +119 -0
- ultralytics/utils/downloads.py +499 -0
- ultralytics/utils/errors.py +43 -0
- ultralytics/utils/export.py +219 -0
- ultralytics/utils/files.py +221 -0
- ultralytics/utils/instance.py +499 -0
- ultralytics/utils/loss.py +813 -0
- ultralytics/utils/metrics.py +1356 -0
- ultralytics/utils/ops.py +885 -0
- ultralytics/utils/patches.py +143 -0
- ultralytics/utils/plotting.py +1011 -0
- ultralytics/utils/tal.py +416 -0
- ultralytics/utils/torch_utils.py +990 -0
- ultralytics/utils/triton.py +116 -0
- ultralytics/utils/tuner.py +159 -0
@@ -0,0 +1,834 @@
|
|
1
|
+
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
|
2
|
+
|
3
|
+
import json
|
4
|
+
from collections import defaultdict
|
5
|
+
from itertools import repeat
|
6
|
+
from multiprocessing.pool import ThreadPool
|
7
|
+
from pathlib import Path
|
8
|
+
|
9
|
+
import cv2
|
10
|
+
import numpy as np
|
11
|
+
import torch
|
12
|
+
from PIL import Image
|
13
|
+
from torch.utils.data import ConcatDataset
|
14
|
+
|
15
|
+
from ultralytics.utils import LOCAL_RANK, LOGGER, NUM_THREADS, TQDM, colorstr
|
16
|
+
from ultralytics.utils.instance import Instances
|
17
|
+
from ultralytics.utils.ops import resample_segments, segments2boxes
|
18
|
+
from ultralytics.utils.torch_utils import TORCHVISION_0_18
|
19
|
+
|
20
|
+
from .augment import (
|
21
|
+
Compose,
|
22
|
+
Format,
|
23
|
+
LetterBox,
|
24
|
+
RandomLoadText,
|
25
|
+
classify_augmentations,
|
26
|
+
classify_transforms,
|
27
|
+
v8_transforms,
|
28
|
+
)
|
29
|
+
from .base import BaseDataset
|
30
|
+
from .converter import merge_multi_segment
|
31
|
+
from .utils import (
|
32
|
+
HELP_URL,
|
33
|
+
check_file_speeds,
|
34
|
+
get_hash,
|
35
|
+
img2label_paths,
|
36
|
+
load_dataset_cache_file,
|
37
|
+
save_dataset_cache_file,
|
38
|
+
verify_image,
|
39
|
+
verify_image_label,
|
40
|
+
)
|
41
|
+
|
42
|
+
# Ultralytics dataset *.cache version, >= 1.0.0 for Ultralytics YOLO models
|
43
|
+
DATASET_CACHE_VERSION = "1.0.3"
|
44
|
+
|
45
|
+
|
46
|
+
class YOLODataset(BaseDataset):
|
47
|
+
"""
|
48
|
+
Dataset class for loading object detection and/or segmentation labels in YOLO format.
|
49
|
+
|
50
|
+
This class supports loading data for object detection, segmentation, pose estimation, and oriented bounding box
|
51
|
+
(OBB) tasks using the YOLO format.
|
52
|
+
|
53
|
+
Attributes:
|
54
|
+
use_segments (bool): Indicates if segmentation masks should be used.
|
55
|
+
use_keypoints (bool): Indicates if keypoints should be used for pose estimation.
|
56
|
+
use_obb (bool): Indicates if oriented bounding boxes should be used.
|
57
|
+
data (dict): Dataset configuration dictionary.
|
58
|
+
|
59
|
+
Methods:
|
60
|
+
cache_labels: Cache dataset labels, check images and read shapes.
|
61
|
+
get_labels: Returns dictionary of labels for YOLO training.
|
62
|
+
build_transforms: Builds and appends transforms to the list.
|
63
|
+
close_mosaic: Sets mosaic, copy_paste and mixup options to 0.0 and builds transformations.
|
64
|
+
update_labels_info: Updates label format for different tasks.
|
65
|
+
collate_fn: Collates data samples into batches.
|
66
|
+
|
67
|
+
Examples:
|
68
|
+
>>> dataset = YOLODataset(img_path="path/to/images", data={"names": {0: "person"}}, task="detect")
|
69
|
+
>>> dataset.get_labels()
|
70
|
+
"""
|
71
|
+
|
72
|
+
def __init__(self, *args, data=None, task="detect", **kwargs):
|
73
|
+
"""
|
74
|
+
Initialize the YOLODataset.
|
75
|
+
|
76
|
+
Args:
|
77
|
+
data (dict, optional): Dataset configuration dictionary.
|
78
|
+
task (str): Task type, one of 'detect', 'segment', 'pose', or 'obb'.
|
79
|
+
*args (Any): Additional positional arguments for the parent class.
|
80
|
+
**kwargs (Any): Additional keyword arguments for the parent class.
|
81
|
+
"""
|
82
|
+
self.use_segments = task == "segment"
|
83
|
+
self.use_keypoints = task == "pose"
|
84
|
+
self.use_obb = task == "obb"
|
85
|
+
self.data = data
|
86
|
+
assert not (self.use_segments and self.use_keypoints), "Can not use both segments and keypoints."
|
87
|
+
super().__init__(*args, channels=self.data["channels"], **kwargs)
|
88
|
+
|
89
|
+
def cache_labels(self, path=Path("./labels.cache")):
|
90
|
+
"""
|
91
|
+
Cache dataset labels, check images and read shapes.
|
92
|
+
|
93
|
+
Args:
|
94
|
+
path (Path): Path where to save the cache file.
|
95
|
+
|
96
|
+
Returns:
|
97
|
+
(dict): Dictionary containing cached labels and related information.
|
98
|
+
"""
|
99
|
+
x = {"labels": []}
|
100
|
+
nm, nf, ne, nc, msgs = 0, 0, 0, 0, [] # number missing, found, empty, corrupt, messages
|
101
|
+
desc = f"{self.prefix}Scanning {path.parent / path.stem}..."
|
102
|
+
total = len(self.im_files)
|
103
|
+
nkpt, ndim = self.data.get("kpt_shape", (0, 0))
|
104
|
+
if self.use_keypoints and (nkpt <= 0 or ndim not in {2, 3}):
|
105
|
+
raise ValueError(
|
106
|
+
"'kpt_shape' in data.yaml missing or incorrect. Should be a list with [number of "
|
107
|
+
"keypoints, number of dims (2 for x,y or 3 for x,y,visible)], i.e. 'kpt_shape: [17, 3]'"
|
108
|
+
)
|
109
|
+
with ThreadPool(NUM_THREADS) as pool:
|
110
|
+
results = pool.imap(
|
111
|
+
func=verify_image_label,
|
112
|
+
iterable=zip(
|
113
|
+
self.im_files,
|
114
|
+
self.label_files,
|
115
|
+
repeat(self.prefix),
|
116
|
+
repeat(self.use_keypoints),
|
117
|
+
repeat(len(self.data["names"])),
|
118
|
+
repeat(nkpt),
|
119
|
+
repeat(ndim),
|
120
|
+
repeat(self.single_cls),
|
121
|
+
),
|
122
|
+
)
|
123
|
+
pbar = TQDM(results, desc=desc, total=total)
|
124
|
+
for im_file, lb, shape, segments, keypoint, nm_f, nf_f, ne_f, nc_f, msg in pbar:
|
125
|
+
nm += nm_f
|
126
|
+
nf += nf_f
|
127
|
+
ne += ne_f
|
128
|
+
nc += nc_f
|
129
|
+
if im_file:
|
130
|
+
x["labels"].append(
|
131
|
+
{
|
132
|
+
"im_file": im_file,
|
133
|
+
"shape": shape,
|
134
|
+
"cls": lb[:, 0:1], # n, 1
|
135
|
+
"bboxes": lb[:, 1:], # n, 4
|
136
|
+
"segments": segments,
|
137
|
+
"keypoints": keypoint,
|
138
|
+
"normalized": True,
|
139
|
+
"bbox_format": "xywh",
|
140
|
+
}
|
141
|
+
)
|
142
|
+
if msg:
|
143
|
+
msgs.append(msg)
|
144
|
+
pbar.desc = f"{desc} {nf} images, {nm + ne} backgrounds, {nc} corrupt"
|
145
|
+
pbar.close()
|
146
|
+
|
147
|
+
if msgs:
|
148
|
+
LOGGER.info("\n".join(msgs))
|
149
|
+
if nf == 0:
|
150
|
+
LOGGER.warning(f"{self.prefix}No labels found in {path}. {HELP_URL}")
|
151
|
+
x["hash"] = get_hash(self.label_files + self.im_files)
|
152
|
+
x["results"] = nf, nm, ne, nc, len(self.im_files)
|
153
|
+
x["msgs"] = msgs # warnings
|
154
|
+
save_dataset_cache_file(self.prefix, path, x, DATASET_CACHE_VERSION)
|
155
|
+
return x
|
156
|
+
|
157
|
+
def get_labels(self):
|
158
|
+
"""
|
159
|
+
Returns dictionary of labels for YOLO training.
|
160
|
+
|
161
|
+
This method loads labels from disk or cache, verifies their integrity, and prepares them for training.
|
162
|
+
|
163
|
+
Returns:
|
164
|
+
(List[dict]): List of label dictionaries, each containing information about an image and its annotations.
|
165
|
+
"""
|
166
|
+
self.label_files = img2label_paths(self.im_files)
|
167
|
+
cache_path = Path(self.label_files[0]).parent.with_suffix(".cache")
|
168
|
+
try:
|
169
|
+
cache, exists = load_dataset_cache_file(cache_path), True # attempt to load a *.cache file
|
170
|
+
assert cache["version"] == DATASET_CACHE_VERSION # matches current version
|
171
|
+
assert cache["hash"] == get_hash(self.label_files + self.im_files) # identical hash
|
172
|
+
except (FileNotFoundError, AssertionError, AttributeError):
|
173
|
+
cache, exists = self.cache_labels(cache_path), False # run cache ops
|
174
|
+
|
175
|
+
# Display cache
|
176
|
+
nf, nm, ne, nc, n = cache.pop("results") # found, missing, empty, corrupt, total
|
177
|
+
if exists and LOCAL_RANK in {-1, 0}:
|
178
|
+
d = f"Scanning {cache_path}... {nf} images, {nm + ne} backgrounds, {nc} corrupt"
|
179
|
+
TQDM(None, desc=self.prefix + d, total=n, initial=n) # display results
|
180
|
+
if cache["msgs"]:
|
181
|
+
LOGGER.info("\n".join(cache["msgs"])) # display warnings
|
182
|
+
|
183
|
+
# Read cache
|
184
|
+
[cache.pop(k) for k in ("hash", "version", "msgs")] # remove items
|
185
|
+
labels = cache["labels"]
|
186
|
+
if not labels:
|
187
|
+
raise RuntimeError(
|
188
|
+
f"No valid images found in {cache_path}. Images with incorrectly formatted labels are ignored. {HELP_URL}"
|
189
|
+
)
|
190
|
+
self.im_files = [lb["im_file"] for lb in labels] # update im_files
|
191
|
+
|
192
|
+
# Check if the dataset is all boxes or all segments
|
193
|
+
lengths = ((len(lb["cls"]), len(lb["bboxes"]), len(lb["segments"])) for lb in labels)
|
194
|
+
len_cls, len_boxes, len_segments = (sum(x) for x in zip(*lengths))
|
195
|
+
if len_segments and len_boxes != len_segments:
|
196
|
+
LOGGER.warning(
|
197
|
+
f"Box and segment counts should be equal, but got len(segments) = {len_segments}, "
|
198
|
+
f"len(boxes) = {len_boxes}. To resolve this only boxes will be used and all segments will be removed. "
|
199
|
+
"To avoid this please supply either a detect or segment dataset, not a detect-segment mixed dataset."
|
200
|
+
)
|
201
|
+
for lb in labels:
|
202
|
+
lb["segments"] = []
|
203
|
+
if len_cls == 0:
|
204
|
+
LOGGER.warning(f"Labels are missing or empty in {cache_path}, training may not work correctly. {HELP_URL}")
|
205
|
+
return labels
|
206
|
+
|
207
|
+
def build_transforms(self, hyp=None):
|
208
|
+
"""
|
209
|
+
Builds and appends transforms to the list.
|
210
|
+
|
211
|
+
Args:
|
212
|
+
hyp (dict, optional): Hyperparameters for transforms.
|
213
|
+
|
214
|
+
Returns:
|
215
|
+
(Compose): Composed transforms.
|
216
|
+
"""
|
217
|
+
if self.augment:
|
218
|
+
hyp.mosaic = hyp.mosaic if self.augment and not self.rect else 0.0
|
219
|
+
hyp.mixup = hyp.mixup if self.augment and not self.rect else 0.0
|
220
|
+
hyp.cutmix = hyp.cutmix if self.augment and not self.rect else 0.0
|
221
|
+
transforms = v8_transforms(self, self.imgsz, hyp)
|
222
|
+
else:
|
223
|
+
transforms = Compose([LetterBox(new_shape=(self.imgsz, self.imgsz), scaleup=False)])
|
224
|
+
transforms.append(
|
225
|
+
Format(
|
226
|
+
bbox_format="xywh",
|
227
|
+
normalize=True,
|
228
|
+
return_mask=self.use_segments,
|
229
|
+
return_keypoint=self.use_keypoints,
|
230
|
+
return_obb=self.use_obb,
|
231
|
+
batch_idx=True,
|
232
|
+
mask_ratio=hyp.mask_ratio,
|
233
|
+
mask_overlap=hyp.overlap_mask,
|
234
|
+
bgr=hyp.bgr if self.augment else 0.0, # only affect training.
|
235
|
+
)
|
236
|
+
)
|
237
|
+
return transforms
|
238
|
+
|
239
|
+
def close_mosaic(self, hyp):
|
240
|
+
"""
|
241
|
+
Disable mosaic, copy_paste, mixup and cutmix augmentations by setting their probabilities to 0.0.
|
242
|
+
|
243
|
+
Args:
|
244
|
+
hyp (dict): Hyperparameters for transforms.
|
245
|
+
"""
|
246
|
+
hyp.mosaic = 0.0
|
247
|
+
hyp.copy_paste = 0.0
|
248
|
+
hyp.mixup = 0.0
|
249
|
+
hyp.cutmix = 0.0
|
250
|
+
self.transforms = self.build_transforms(hyp)
|
251
|
+
|
252
|
+
def update_labels_info(self, label):
|
253
|
+
"""
|
254
|
+
Custom your label format here.
|
255
|
+
|
256
|
+
Args:
|
257
|
+
label (dict): Label dictionary containing bboxes, segments, keypoints, etc.
|
258
|
+
|
259
|
+
Returns:
|
260
|
+
(dict): Updated label dictionary with instances.
|
261
|
+
|
262
|
+
Note:
|
263
|
+
cls is not with bboxes now, classification and semantic segmentation need an independent cls label
|
264
|
+
Can also support classification and semantic segmentation by adding or removing dict keys there.
|
265
|
+
"""
|
266
|
+
bboxes = label.pop("bboxes")
|
267
|
+
segments = label.pop("segments", [])
|
268
|
+
keypoints = label.pop("keypoints", None)
|
269
|
+
bbox_format = label.pop("bbox_format")
|
270
|
+
normalized = label.pop("normalized")
|
271
|
+
|
272
|
+
# NOTE: do NOT resample oriented boxes
|
273
|
+
segment_resamples = 100 if self.use_obb else 1000
|
274
|
+
if len(segments) > 0:
|
275
|
+
# make sure segments interpolate correctly if original length is greater than segment_resamples
|
276
|
+
max_len = max(len(s) for s in segments)
|
277
|
+
segment_resamples = (max_len + 1) if segment_resamples < max_len else segment_resamples
|
278
|
+
# list[np.array(segment_resamples, 2)] * num_samples
|
279
|
+
segments = np.stack(resample_segments(segments, n=segment_resamples), axis=0)
|
280
|
+
else:
|
281
|
+
segments = np.zeros((0, segment_resamples, 2), dtype=np.float32)
|
282
|
+
label["instances"] = Instances(bboxes, segments, keypoints, bbox_format=bbox_format, normalized=normalized)
|
283
|
+
return label
|
284
|
+
|
285
|
+
@staticmethod
|
286
|
+
def collate_fn(batch):
|
287
|
+
"""
|
288
|
+
Collates data samples into batches.
|
289
|
+
|
290
|
+
Args:
|
291
|
+
batch (List[dict]): List of dictionaries containing sample data.
|
292
|
+
|
293
|
+
Returns:
|
294
|
+
(dict): Collated batch with stacked tensors.
|
295
|
+
"""
|
296
|
+
new_batch = {}
|
297
|
+
batch = [dict(sorted(b.items())) for b in batch] # make sure the keys are in the same order
|
298
|
+
keys = batch[0].keys()
|
299
|
+
values = list(zip(*[list(b.values()) for b in batch]))
|
300
|
+
for i, k in enumerate(keys):
|
301
|
+
value = values[i]
|
302
|
+
if k in {"img", "text_feats"}:
|
303
|
+
value = torch.stack(value, 0)
|
304
|
+
elif k == "visuals":
|
305
|
+
value = torch.nn.utils.rnn.pad_sequence(value, batch_first=True)
|
306
|
+
if k in {"masks", "keypoints", "bboxes", "cls", "segments", "obb"}:
|
307
|
+
value = torch.cat(value, 0)
|
308
|
+
new_batch[k] = value
|
309
|
+
new_batch["batch_idx"] = list(new_batch["batch_idx"])
|
310
|
+
for i in range(len(new_batch["batch_idx"])):
|
311
|
+
new_batch["batch_idx"][i] += i # add target image index for build_targets()
|
312
|
+
new_batch["batch_idx"] = torch.cat(new_batch["batch_idx"], 0)
|
313
|
+
return new_batch
|
314
|
+
|
315
|
+
|
316
|
+
class YOLOMultiModalDataset(YOLODataset):
|
317
|
+
"""
|
318
|
+
Dataset class for loading object detection and/or segmentation labels in YOLO format with multi-modal support.
|
319
|
+
|
320
|
+
This class extends YOLODataset to add text information for multi-modal model training, enabling models to
|
321
|
+
process both image and text data.
|
322
|
+
|
323
|
+
Methods:
|
324
|
+
update_labels_info: Adds text information for multi-modal model training.
|
325
|
+
build_transforms: Enhances data transformations with text augmentation.
|
326
|
+
|
327
|
+
Examples:
|
328
|
+
>>> dataset = YOLOMultiModalDataset(img_path="path/to/images", data={"names": {0: "person"}}, task="detect")
|
329
|
+
>>> batch = next(iter(dataset))
|
330
|
+
>>> print(batch.keys()) # Should include 'texts'
|
331
|
+
"""
|
332
|
+
|
333
|
+
def __init__(self, *args, data=None, task="detect", **kwargs):
|
334
|
+
"""
|
335
|
+
Initialize a YOLOMultiModalDataset.
|
336
|
+
|
337
|
+
Args:
|
338
|
+
data (dict, optional): Dataset configuration dictionary.
|
339
|
+
task (str): Task type, one of 'detect', 'segment', 'pose', or 'obb'.
|
340
|
+
*args (Any): Additional positional arguments for the parent class.
|
341
|
+
**kwargs (Any): Additional keyword arguments for the parent class.
|
342
|
+
"""
|
343
|
+
super().__init__(*args, data=data, task=task, **kwargs)
|
344
|
+
|
345
|
+
def update_labels_info(self, label):
|
346
|
+
"""
|
347
|
+
Add texts information for multi-modal model training.
|
348
|
+
|
349
|
+
Args:
|
350
|
+
label (dict): Label dictionary containing bboxes, segments, keypoints, etc.
|
351
|
+
|
352
|
+
Returns:
|
353
|
+
(dict): Updated label dictionary with instances and texts.
|
354
|
+
"""
|
355
|
+
labels = super().update_labels_info(label)
|
356
|
+
# NOTE: some categories are concatenated with its synonyms by `/`.
|
357
|
+
# NOTE: and `RandomLoadText` would randomly select one of them if there are multiple words.
|
358
|
+
labels["texts"] = [v.split("/") for _, v in self.data["names"].items()]
|
359
|
+
|
360
|
+
return labels
|
361
|
+
|
362
|
+
def build_transforms(self, hyp=None):
|
363
|
+
"""
|
364
|
+
Enhances data transformations with optional text augmentation for multi-modal training.
|
365
|
+
|
366
|
+
Args:
|
367
|
+
hyp (dict, optional): Hyperparameters for transforms.
|
368
|
+
|
369
|
+
Returns:
|
370
|
+
(Compose): Composed transforms including text augmentation if applicable.
|
371
|
+
"""
|
372
|
+
transforms = super().build_transforms(hyp)
|
373
|
+
if self.augment:
|
374
|
+
# NOTE: hard-coded the args for now.
|
375
|
+
# NOTE: this implementation is different from official yoloe,
|
376
|
+
# the strategy of selecting negative is restricted in one dataset,
|
377
|
+
# while official pre-saved neg embeddings from all datasets at once.
|
378
|
+
transform = RandomLoadText(
|
379
|
+
max_samples=min(self.data["nc"], 80),
|
380
|
+
padding=True,
|
381
|
+
padding_value=self._get_neg_texts(self.category_freq),
|
382
|
+
)
|
383
|
+
transforms.insert(-1, transform)
|
384
|
+
return transforms
|
385
|
+
|
386
|
+
@property
|
387
|
+
def category_names(self):
|
388
|
+
"""
|
389
|
+
Return category names for the dataset.
|
390
|
+
|
391
|
+
Returns:
|
392
|
+
(Set[str]): List of class names.
|
393
|
+
"""
|
394
|
+
names = self.data["names"].values()
|
395
|
+
return {n.strip() for name in names for n in name.split("/")} # category names
|
396
|
+
|
397
|
+
@property
|
398
|
+
def category_freq(self):
|
399
|
+
"""Return frequency of each category in the dataset."""
|
400
|
+
texts = [v.split("/") for v in self.data["names"].values()]
|
401
|
+
category_freq = defaultdict(int)
|
402
|
+
for label in self.labels:
|
403
|
+
for c in label["cls"].squeeze(-1): # to check
|
404
|
+
text = texts[int(c)]
|
405
|
+
for t in text:
|
406
|
+
t = t.strip()
|
407
|
+
category_freq[t] += 1
|
408
|
+
return category_freq
|
409
|
+
|
410
|
+
@staticmethod
|
411
|
+
def _get_neg_texts(category_freq, threshold=100):
|
412
|
+
"""Get negative text samples based on frequency threshold."""
|
413
|
+
return [k for k, v in category_freq.items() if v >= threshold]
|
414
|
+
|
415
|
+
|
416
|
+
class GroundingDataset(YOLODataset):
|
417
|
+
"""
|
418
|
+
Handles object detection tasks by loading annotations from a specified JSON file, supporting YOLO format.
|
419
|
+
|
420
|
+
This dataset is designed for grounding tasks where annotations are provided in a JSON file rather than
|
421
|
+
the standard YOLO format text files.
|
422
|
+
|
423
|
+
Attributes:
|
424
|
+
json_file (str): Path to the JSON file containing annotations.
|
425
|
+
|
426
|
+
Methods:
|
427
|
+
get_img_files: Returns empty list as image files are read in get_labels.
|
428
|
+
get_labels: Loads annotations from a JSON file and prepares them for training.
|
429
|
+
build_transforms: Configures augmentations for training with optional text loading.
|
430
|
+
|
431
|
+
Examples:
|
432
|
+
>>> dataset = GroundingDataset(img_path="path/to/images", json_file="annotations.json", task="detect")
|
433
|
+
>>> len(dataset) # Number of valid images with annotations
|
434
|
+
"""
|
435
|
+
|
436
|
+
def __init__(self, *args, task="detect", json_file="", **kwargs):
|
437
|
+
"""
|
438
|
+
Initialize a GroundingDataset for object detection.
|
439
|
+
|
440
|
+
Args:
|
441
|
+
json_file (str): Path to the JSON file containing annotations.
|
442
|
+
task (str): Must be 'detect' or 'segment' for GroundingDataset.
|
443
|
+
*args (Any): Additional positional arguments for the parent class.
|
444
|
+
**kwargs (Any): Additional keyword arguments for the parent class.
|
445
|
+
"""
|
446
|
+
assert task in {"detect", "segment"}, "GroundingDataset currently only supports `detect` and `segment` tasks"
|
447
|
+
self.json_file = json_file
|
448
|
+
super().__init__(*args, task=task, data={"channels": 3}, **kwargs)
|
449
|
+
|
450
|
+
def get_img_files(self, img_path):
|
451
|
+
"""
|
452
|
+
The image files would be read in `get_labels` function, return empty list here.
|
453
|
+
|
454
|
+
Args:
|
455
|
+
img_path (str): Path to the directory containing images.
|
456
|
+
|
457
|
+
Returns:
|
458
|
+
(list): Empty list as image files are read in get_labels.
|
459
|
+
"""
|
460
|
+
return []
|
461
|
+
|
462
|
+
def verify_labels(self, labels):
|
463
|
+
"""Verify the number of instances in the dataset matches expected counts."""
|
464
|
+
instance_count = sum(label["bboxes"].shape[0] for label in labels)
|
465
|
+
if "final_mixed_train_no_coco_segm" in self.json_file:
|
466
|
+
assert instance_count == 3662344
|
467
|
+
elif "final_mixed_train_no_coco" in self.json_file:
|
468
|
+
assert instance_count == 3681235
|
469
|
+
elif "final_flickr_separateGT_train_segm" in self.json_file:
|
470
|
+
assert instance_count == 638214
|
471
|
+
elif "final_flickr_separateGT_train" in self.json_file:
|
472
|
+
assert instance_count == 640704
|
473
|
+
else:
|
474
|
+
assert False
|
475
|
+
|
476
|
+
def cache_labels(self, path=Path("./labels.cache")):
|
477
|
+
"""
|
478
|
+
Loads annotations from a JSON file, filters, and normalizes bounding boxes for each image.
|
479
|
+
|
480
|
+
Args:
|
481
|
+
path (Path): Path where to save the cache file.
|
482
|
+
|
483
|
+
Returns:
|
484
|
+
(dict): Dictionary containing cached labels and related information.
|
485
|
+
"""
|
486
|
+
x = {"labels": []}
|
487
|
+
LOGGER.info("Loading annotation file...")
|
488
|
+
with open(self.json_file) as f:
|
489
|
+
annotations = json.load(f)
|
490
|
+
images = {f"{x['id']:d}": x for x in annotations["images"]}
|
491
|
+
img_to_anns = defaultdict(list)
|
492
|
+
for ann in annotations["annotations"]:
|
493
|
+
img_to_anns[ann["image_id"]].append(ann)
|
494
|
+
for img_id, anns in TQDM(img_to_anns.items(), desc=f"Reading annotations {self.json_file}"):
|
495
|
+
img = images[f"{img_id:d}"]
|
496
|
+
h, w, f = img["height"], img["width"], img["file_name"]
|
497
|
+
im_file = Path(self.img_path) / f
|
498
|
+
if not im_file.exists():
|
499
|
+
continue
|
500
|
+
self.im_files.append(str(im_file))
|
501
|
+
bboxes = []
|
502
|
+
segments = []
|
503
|
+
cat2id = {}
|
504
|
+
texts = []
|
505
|
+
for ann in anns:
|
506
|
+
if ann["iscrowd"]:
|
507
|
+
continue
|
508
|
+
box = np.array(ann["bbox"], dtype=np.float32)
|
509
|
+
box[:2] += box[2:] / 2
|
510
|
+
box[[0, 2]] /= float(w)
|
511
|
+
box[[1, 3]] /= float(h)
|
512
|
+
if box[2] <= 0 or box[3] <= 0:
|
513
|
+
continue
|
514
|
+
|
515
|
+
caption = img["caption"]
|
516
|
+
cat_name = " ".join([caption[t[0] : t[1]] for t in ann["tokens_positive"]]).lower().strip()
|
517
|
+
if not cat_name:
|
518
|
+
continue
|
519
|
+
|
520
|
+
if cat_name not in cat2id:
|
521
|
+
cat2id[cat_name] = len(cat2id)
|
522
|
+
texts.append([cat_name])
|
523
|
+
cls = cat2id[cat_name] # class
|
524
|
+
box = [cls] + box.tolist()
|
525
|
+
if box not in bboxes:
|
526
|
+
bboxes.append(box)
|
527
|
+
if ann.get("segmentation") is not None:
|
528
|
+
if len(ann["segmentation"]) == 0:
|
529
|
+
segments.append(box)
|
530
|
+
continue
|
531
|
+
elif len(ann["segmentation"]) > 1:
|
532
|
+
s = merge_multi_segment(ann["segmentation"])
|
533
|
+
s = (np.concatenate(s, axis=0) / np.array([w, h], dtype=np.float32)).reshape(-1).tolist()
|
534
|
+
else:
|
535
|
+
s = [j for i in ann["segmentation"] for j in i] # all segments concatenated
|
536
|
+
s = (
|
537
|
+
(np.array(s, dtype=np.float32).reshape(-1, 2) / np.array([w, h], dtype=np.float32))
|
538
|
+
.reshape(-1)
|
539
|
+
.tolist()
|
540
|
+
)
|
541
|
+
s = [cls] + s
|
542
|
+
segments.append(s)
|
543
|
+
lb = np.array(bboxes, dtype=np.float32) if len(bboxes) else np.zeros((0, 5), dtype=np.float32)
|
544
|
+
|
545
|
+
if segments:
|
546
|
+
classes = np.array([x[0] for x in segments], dtype=np.float32)
|
547
|
+
segments = [np.array(x[1:], dtype=np.float32).reshape(-1, 2) for x in segments] # (cls, xy1...)
|
548
|
+
lb = np.concatenate((classes.reshape(-1, 1), segments2boxes(segments)), 1) # (cls, xywh)
|
549
|
+
lb = np.array(lb, dtype=np.float32)
|
550
|
+
|
551
|
+
x["labels"].append(
|
552
|
+
{
|
553
|
+
"im_file": im_file,
|
554
|
+
"shape": (h, w),
|
555
|
+
"cls": lb[:, 0:1], # n, 1
|
556
|
+
"bboxes": lb[:, 1:], # n, 4
|
557
|
+
"segments": segments,
|
558
|
+
"normalized": True,
|
559
|
+
"bbox_format": "xywh",
|
560
|
+
"texts": texts,
|
561
|
+
}
|
562
|
+
)
|
563
|
+
x["hash"] = get_hash(self.json_file)
|
564
|
+
save_dataset_cache_file(self.prefix, path, x, DATASET_CACHE_VERSION)
|
565
|
+
return x
|
566
|
+
|
567
|
+
def get_labels(self):
|
568
|
+
"""
|
569
|
+
Load labels from cache or generate them from JSON file.
|
570
|
+
|
571
|
+
Returns:
|
572
|
+
(List[dict]): List of label dictionaries, each containing information about an image and its annotations.
|
573
|
+
"""
|
574
|
+
cache_path = Path(self.json_file).with_suffix(".cache")
|
575
|
+
try:
|
576
|
+
cache, _ = load_dataset_cache_file(cache_path), True # attempt to load a *.cache file
|
577
|
+
assert cache["version"] == DATASET_CACHE_VERSION # matches current version
|
578
|
+
assert cache["hash"] == get_hash(self.json_file) # identical hash
|
579
|
+
except (FileNotFoundError, AssertionError, AttributeError):
|
580
|
+
cache, _ = self.cache_labels(cache_path), False # run cache ops
|
581
|
+
[cache.pop(k) for k in ("hash", "version")] # remove items
|
582
|
+
labels = cache["labels"]
|
583
|
+
# self.verify_labels(labels)
|
584
|
+
self.im_files = [str(label["im_file"]) for label in labels]
|
585
|
+
if LOCAL_RANK in {-1, 0}:
|
586
|
+
LOGGER.info(f"Load {self.json_file} from cache file {cache_path}")
|
587
|
+
return labels
|
588
|
+
|
589
|
+
def build_transforms(self, hyp=None):
|
590
|
+
"""
|
591
|
+
Configures augmentations for training with optional text loading.
|
592
|
+
|
593
|
+
Args:
|
594
|
+
hyp (dict, optional): Hyperparameters for transforms.
|
595
|
+
|
596
|
+
Returns:
|
597
|
+
(Compose): Composed transforms including text augmentation if applicable.
|
598
|
+
"""
|
599
|
+
transforms = super().build_transforms(hyp)
|
600
|
+
if self.augment:
|
601
|
+
# NOTE: hard-coded the args for now.
|
602
|
+
# NOTE: this implementation is different from official yoloe,
|
603
|
+
# the strategy of selecting negative is restricted in one dataset,
|
604
|
+
# while official pre-saved neg embeddings from all datasets at once.
|
605
|
+
transform = RandomLoadText(
|
606
|
+
max_samples=80,
|
607
|
+
padding=True,
|
608
|
+
padding_value=self._get_neg_texts(self.category_freq),
|
609
|
+
)
|
610
|
+
transforms.insert(-1, transform)
|
611
|
+
return transforms
|
612
|
+
|
613
|
+
@property
|
614
|
+
def category_names(self):
|
615
|
+
"""Return unique category names from the dataset."""
|
616
|
+
return {t.strip() for label in self.labels for text in label["texts"] for t in text}
|
617
|
+
|
618
|
+
@property
|
619
|
+
def category_freq(self):
|
620
|
+
"""Return frequency of each category in the dataset."""
|
621
|
+
category_freq = defaultdict(int)
|
622
|
+
for label in self.labels:
|
623
|
+
for text in label["texts"]:
|
624
|
+
for t in text:
|
625
|
+
t = t.strip()
|
626
|
+
category_freq[t] += 1
|
627
|
+
return category_freq
|
628
|
+
|
629
|
+
@staticmethod
|
630
|
+
def _get_neg_texts(category_freq, threshold=100):
|
631
|
+
"""Get negative text samples based on frequency threshold."""
|
632
|
+
return [k for k, v in category_freq.items() if v >= threshold]
|
633
|
+
|
634
|
+
|
635
|
+
class YOLOConcatDataset(ConcatDataset):
|
636
|
+
"""
|
637
|
+
Dataset as a concatenation of multiple datasets.
|
638
|
+
|
639
|
+
This class is useful to assemble different existing datasets for YOLO training, ensuring they use the same
|
640
|
+
collation function.
|
641
|
+
|
642
|
+
Methods:
|
643
|
+
collate_fn: Static method that collates data samples into batches using YOLODataset's collation function.
|
644
|
+
|
645
|
+
Examples:
|
646
|
+
>>> dataset1 = YOLODataset(...)
|
647
|
+
>>> dataset2 = YOLODataset(...)
|
648
|
+
>>> combined_dataset = YOLOConcatDataset([dataset1, dataset2])
|
649
|
+
"""
|
650
|
+
|
651
|
+
@staticmethod
|
652
|
+
def collate_fn(batch):
|
653
|
+
"""
|
654
|
+
Collates data samples into batches.
|
655
|
+
|
656
|
+
Args:
|
657
|
+
batch (List[dict]): List of dictionaries containing sample data.
|
658
|
+
|
659
|
+
Returns:
|
660
|
+
(dict): Collated batch with stacked tensors.
|
661
|
+
"""
|
662
|
+
return YOLODataset.collate_fn(batch)
|
663
|
+
|
664
|
+
def close_mosaic(self, hyp):
|
665
|
+
"""
|
666
|
+
Sets mosaic, copy_paste and mixup options to 0.0 and builds transformations.
|
667
|
+
|
668
|
+
Args:
|
669
|
+
hyp (dict): Hyperparameters for transforms.
|
670
|
+
"""
|
671
|
+
for dataset in self.datasets:
|
672
|
+
if not hasattr(dataset, "close_mosaic"):
|
673
|
+
continue
|
674
|
+
dataset.close_mosaic(hyp)
|
675
|
+
|
676
|
+
|
677
|
+
# TODO: support semantic segmentation
|
678
|
+
class SemanticDataset(BaseDataset):
|
679
|
+
"""Semantic Segmentation Dataset."""
|
680
|
+
|
681
|
+
def __init__(self):
|
682
|
+
"""Initialize a SemanticDataset object."""
|
683
|
+
super().__init__()
|
684
|
+
|
685
|
+
|
686
|
+
class ClassificationDataset:
|
687
|
+
"""
|
688
|
+
Extends torchvision ImageFolder to support YOLO classification tasks.
|
689
|
+
|
690
|
+
This class offers functionalities like image augmentation, caching, and verification. It's designed to efficiently
|
691
|
+
handle large datasets for training deep learning models, with optional image transformations and caching mechanisms
|
692
|
+
to speed up training.
|
693
|
+
|
694
|
+
Attributes:
|
695
|
+
cache_ram (bool): Indicates if caching in RAM is enabled.
|
696
|
+
cache_disk (bool): Indicates if caching on disk is enabled.
|
697
|
+
samples (list): A list of tuples, each containing the path to an image, its class index, path to its .npy cache
|
698
|
+
file (if caching on disk), and optionally the loaded image array (if caching in RAM).
|
699
|
+
torch_transforms (callable): PyTorch transforms to be applied to the images.
|
700
|
+
root (str): Root directory of the dataset.
|
701
|
+
prefix (str): Prefix for logging and cache filenames.
|
702
|
+
|
703
|
+
Methods:
|
704
|
+
__getitem__: Returns subset of data and targets corresponding to given indices.
|
705
|
+
__len__: Returns the total number of samples in the dataset.
|
706
|
+
verify_images: Verifies all images in dataset.
|
707
|
+
"""
|
708
|
+
|
709
|
+
def __init__(self, root, args, augment=False, prefix=""):
|
710
|
+
"""
|
711
|
+
Initialize YOLO object with root, image size, augmentations, and cache settings.
|
712
|
+
|
713
|
+
Args:
|
714
|
+
root (str): Path to the dataset directory where images are stored in a class-specific folder structure.
|
715
|
+
args (Namespace): Configuration containing dataset-related settings such as image size, augmentation
|
716
|
+
parameters, and cache settings.
|
717
|
+
augment (bool, optional): Whether to apply augmentations to the dataset.
|
718
|
+
prefix (str, optional): Prefix for logging and cache filenames, aiding in dataset identification.
|
719
|
+
"""
|
720
|
+
import torchvision # scope for faster 'import ultralytics'
|
721
|
+
|
722
|
+
# Base class assigned as attribute rather than used as base class to allow for scoping slow torchvision import
|
723
|
+
if TORCHVISION_0_18: # 'allow_empty' argument first introduced in torchvision 0.18
|
724
|
+
self.base = torchvision.datasets.ImageFolder(root=root, allow_empty=True)
|
725
|
+
else:
|
726
|
+
self.base = torchvision.datasets.ImageFolder(root=root)
|
727
|
+
self.samples = self.base.samples
|
728
|
+
self.root = self.base.root
|
729
|
+
|
730
|
+
# Initialize attributes
|
731
|
+
if augment and args.fraction < 1.0: # reduce training fraction
|
732
|
+
self.samples = self.samples[: round(len(self.samples) * args.fraction)]
|
733
|
+
self.prefix = colorstr(f"{prefix}: ") if prefix else ""
|
734
|
+
self.cache_ram = args.cache is True or str(args.cache).lower() == "ram" # cache images into RAM
|
735
|
+
if self.cache_ram:
|
736
|
+
LOGGER.warning(
|
737
|
+
"Classification `cache_ram` training has known memory leak in "
|
738
|
+
"https://github.com/ultralytics/ultralytics/issues/9824, setting `cache_ram=False`."
|
739
|
+
)
|
740
|
+
self.cache_ram = False
|
741
|
+
self.cache_disk = str(args.cache).lower() == "disk" # cache images on hard drive as uncompressed *.npy files
|
742
|
+
self.samples = self.verify_images() # filter out bad images
|
743
|
+
self.samples = [list(x) + [Path(x[0]).with_suffix(".npy"), None] for x in self.samples] # file, index, npy, im
|
744
|
+
scale = (1.0 - args.scale, 1.0) # (0.08, 1.0)
|
745
|
+
self.torch_transforms = (
|
746
|
+
classify_augmentations(
|
747
|
+
size=args.imgsz,
|
748
|
+
scale=scale,
|
749
|
+
hflip=args.fliplr,
|
750
|
+
vflip=args.flipud,
|
751
|
+
erasing=args.erasing,
|
752
|
+
auto_augment=args.auto_augment,
|
753
|
+
hsv_h=args.hsv_h,
|
754
|
+
hsv_s=args.hsv_s,
|
755
|
+
hsv_v=args.hsv_v,
|
756
|
+
)
|
757
|
+
if augment
|
758
|
+
else classify_transforms(size=args.imgsz)
|
759
|
+
)
|
760
|
+
|
761
|
+
def __getitem__(self, i):
|
762
|
+
"""
|
763
|
+
Returns subset of data and targets corresponding to given indices.
|
764
|
+
|
765
|
+
Args:
|
766
|
+
i (int): Index of the sample to retrieve.
|
767
|
+
|
768
|
+
Returns:
|
769
|
+
(dict): Dictionary containing the image and its class index.
|
770
|
+
"""
|
771
|
+
f, j, fn, im = self.samples[i] # filename, index, filename.with_suffix('.npy'), image
|
772
|
+
if self.cache_ram:
|
773
|
+
if im is None: # Warning: two separate if statements required here, do not combine this with previous line
|
774
|
+
im = self.samples[i][3] = cv2.imread(f)
|
775
|
+
elif self.cache_disk:
|
776
|
+
if not fn.exists(): # load npy
|
777
|
+
np.save(fn.as_posix(), cv2.imread(f), allow_pickle=False)
|
778
|
+
im = np.load(fn)
|
779
|
+
else: # read image
|
780
|
+
im = cv2.imread(f) # BGR
|
781
|
+
# Convert NumPy array to PIL image
|
782
|
+
im = Image.fromarray(cv2.cvtColor(im, cv2.COLOR_BGR2RGB))
|
783
|
+
sample = self.torch_transforms(im)
|
784
|
+
return {"img": sample, "cls": j}
|
785
|
+
|
786
|
+
def __len__(self) -> int:
|
787
|
+
"""Return the total number of samples in the dataset."""
|
788
|
+
return len(self.samples)
|
789
|
+
|
790
|
+
def verify_images(self):
|
791
|
+
"""
|
792
|
+
Verify all images in dataset.
|
793
|
+
|
794
|
+
Returns:
|
795
|
+
(list): List of valid samples after verification.
|
796
|
+
"""
|
797
|
+
desc = f"{self.prefix}Scanning {self.root}..."
|
798
|
+
path = Path(self.root).with_suffix(".cache") # *.cache file path
|
799
|
+
|
800
|
+
try:
|
801
|
+
check_file_speeds([file for (file, _) in self.samples[:5]], prefix=self.prefix) # check image read speeds
|
802
|
+
cache = load_dataset_cache_file(path) # attempt to load a *.cache file
|
803
|
+
assert cache["version"] == DATASET_CACHE_VERSION # matches current version
|
804
|
+
assert cache["hash"] == get_hash([x[0] for x in self.samples]) # identical hash
|
805
|
+
nf, nc, n, samples = cache.pop("results") # found, missing, empty, corrupt, total
|
806
|
+
if LOCAL_RANK in {-1, 0}:
|
807
|
+
d = f"{desc} {nf} images, {nc} corrupt"
|
808
|
+
TQDM(None, desc=d, total=n, initial=n)
|
809
|
+
if cache["msgs"]:
|
810
|
+
LOGGER.info("\n".join(cache["msgs"])) # display warnings
|
811
|
+
return samples
|
812
|
+
|
813
|
+
except (FileNotFoundError, AssertionError, AttributeError):
|
814
|
+
# Run scan if *.cache retrieval failed
|
815
|
+
nf, nc, msgs, samples, x = 0, 0, [], [], {}
|
816
|
+
with ThreadPool(NUM_THREADS) as pool:
|
817
|
+
results = pool.imap(func=verify_image, iterable=zip(self.samples, repeat(self.prefix)))
|
818
|
+
pbar = TQDM(results, desc=desc, total=len(self.samples))
|
819
|
+
for sample, nf_f, nc_f, msg in pbar:
|
820
|
+
if nf_f:
|
821
|
+
samples.append(sample)
|
822
|
+
if msg:
|
823
|
+
msgs.append(msg)
|
824
|
+
nf += nf_f
|
825
|
+
nc += nc_f
|
826
|
+
pbar.desc = f"{desc} {nf} images, {nc} corrupt"
|
827
|
+
pbar.close()
|
828
|
+
if msgs:
|
829
|
+
LOGGER.info("\n".join(msgs))
|
830
|
+
x["hash"] = get_hash([x[0] for x in self.samples])
|
831
|
+
x["results"] = nf, nc, len(samples), samples
|
832
|
+
x["msgs"] = msgs # warnings
|
833
|
+
save_dataset_cache_file(self.prefix, path, x, DATASET_CACHE_VERSION)
|
834
|
+
return samples
|