Reference for ultralytics/data/dataset.py
Note
This file is available at https://github.com/ultralytics/ultralytics/blob/main/ultralytics/data/dataset.py. If you spot a problem please help fix it by contributing a Pull Request 🛠️. Thank you 🙏!
ultralytics.data.dataset.YOLODataset
YOLODataset(*args, data: Optional[Dict] = None, task: str = 'detect', **kwargs)
Bases: BaseDataset
Dataset class for loading object detection and/or segmentation labels in YOLO format.
This class supports loading data for object detection, segmentation, pose estimation, and oriented bounding box (OBB) tasks using the YOLO format.
Attributes:
Name | Type | Description |
---|---|---|
use_segments |
bool
|
Indicates if segmentation masks should be used. |
use_keypoints |
bool
|
Indicates if keypoints should be used for pose estimation. |
use_obb |
bool
|
Indicates if oriented bounding boxes should be used. |
data |
dict
|
Dataset configuration dictionary. |
Methods:
Name | Description |
---|---|
cache_labels |
Cache dataset labels, check images and read shapes. |
get_labels |
Return dictionary of labels for YOLO training. |
build_transforms |
Build and append transforms to the list. |
close_mosaic |
Set mosaic, copy_paste and mixup options to 0.0 and build transformations. |
update_labels_info |
Update label format for different tasks. |
collate_fn |
Collate data samples into batches. |
Examples:
>>> dataset = YOLODataset(img_path="path/to/images", data={"names": {0: "person"}}, task="detect")
>>> dataset.get_labels()
Parameters:
Name | Type | Description | Default |
---|---|---|---|
data
|
dict
|
Dataset configuration dictionary. |
None
|
task
|
str
|
Task type, one of 'detect', 'segment', 'pose', or 'obb'. |
'detect'
|
*args
|
Any
|
Additional positional arguments for the parent class. |
()
|
**kwargs
|
Any
|
Additional keyword arguments for the parent class. |
{}
|
Source code in ultralytics/data/dataset.py
73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 |
|
build_transforms
build_transforms(hyp: Optional[Dict] = None) -> Compose
Build and append transforms to the list.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
hyp
|
dict
|
Hyperparameters for transforms. |
None
|
Returns:
Type | Description |
---|---|
Compose
|
Composed transforms. |
Source code in ultralytics/data/dataset.py
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 |
|
cache_labels
cache_labels(path: Path = Path('./labels.cache')) -> Dict
Cache dataset labels, check images and read shapes.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
path
|
Path
|
Path where to save the cache file. |
Path('./labels.cache')
|
Returns:
Type | Description |
---|---|
dict
|
Dictionary containing cached labels and related information. |
Source code in ultralytics/data/dataset.py
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 |
|
close_mosaic
close_mosaic(hyp: Dict) -> None
Disable mosaic, copy_paste, mixup and cutmix augmentations by setting their probabilities to 0.0.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
hyp
|
dict
|
Hyperparameters for transforms. |
required |
Source code in ultralytics/data/dataset.py
240 241 242 243 244 245 246 247 248 249 250 251 |
|
collate_fn
staticmethod
collate_fn(batch: List[Dict]) -> Dict
Collate data samples into batches.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
batch
|
List[dict]
|
List of dictionaries containing sample data. |
required |
Returns:
Type | Description |
---|---|
dict
|
Collated batch with stacked tensors. |
Source code in ultralytics/data/dataset.py
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 |
|
get_labels
get_labels() -> List[Dict]
Return dictionary of labels for YOLO training.
This method loads labels from disk or cache, verifies their integrity, and prepares them for training.
Returns:
Type | Description |
---|---|
List[dict]
|
List of label dictionaries, each containing information about an image and its annotations. |
Source code in ultralytics/data/dataset.py
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 |
|
update_labels_info
update_labels_info(label: Dict) -> Dict
Update label format for different tasks.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
label
|
dict
|
Label dictionary containing bboxes, segments, keypoints, etc. |
required |
Returns:
Type | Description |
---|---|
dict
|
Updated label dictionary with instances. |
Note
cls is not with bboxes now, classification and semantic segmentation need an independent cls label Can also support classification and semantic segmentation by adding or removing dict keys there.
Source code in ultralytics/data/dataset.py
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 |
|
ultralytics.data.dataset.YOLOMultiModalDataset
YOLOMultiModalDataset(
*args, data: Optional[Dict] = None, task: str = "detect", **kwargs
)
Bases: YOLODataset
Dataset class for loading object detection and/or segmentation labels in YOLO format with multi-modal support.
This class extends YOLODataset to add text information for multi-modal model training, enabling models to process both image and text data.
Methods:
Name | Description |
---|---|
update_labels_info |
Add text information for multi-modal model training. |
build_transforms |
Enhance data transformations with text augmentation. |
Examples:
>>> dataset = YOLOMultiModalDataset(img_path="path/to/images", data={"names": {0: "person"}}, task="detect")
>>> batch = next(iter(dataset))
>>> print(batch.keys()) # Should include 'texts'
Parameters:
Name | Type | Description | Default |
---|---|---|---|
data
|
dict
|
Dataset configuration dictionary. |
None
|
task
|
str
|
Task type, one of 'detect', 'segment', 'pose', or 'obb'. |
'detect'
|
*args
|
Any
|
Additional positional arguments for the parent class. |
()
|
**kwargs
|
Any
|
Additional keyword arguments for the parent class. |
{}
|
Source code in ultralytics/data/dataset.py
334 335 336 337 338 339 340 341 342 343 344 |
|
category_freq
property
category_freq
Return frequency of each category in the dataset.
category_names
property
category_names
Return category names for the dataset.
Returns:
Type | Description |
---|---|
Set[str]
|
List of class names. |
build_transforms
build_transforms(hyp: Optional[Dict] = None) -> Compose
Enhance data transformations with optional text augmentation for multi-modal training.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
hyp
|
dict
|
Hyperparameters for transforms. |
None
|
Returns:
Type | Description |
---|---|
Compose
|
Composed transforms including text augmentation if applicable. |
Source code in ultralytics/data/dataset.py
363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 |
|
update_labels_info
update_labels_info(label: Dict) -> Dict
Add text information for multi-modal model training.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
label
|
dict
|
Label dictionary containing bboxes, segments, keypoints, etc. |
required |
Returns:
Type | Description |
---|---|
dict
|
Updated label dictionary with instances and texts. |
Source code in ultralytics/data/dataset.py
346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 |
|
ultralytics.data.dataset.GroundingDataset
GroundingDataset(*args, task: str = 'detect', json_file: str = '', **kwargs)
Bases: YOLODataset
Dataset class for object detection tasks using annotations from a JSON file in grounding format.
This dataset is designed for grounding tasks where annotations are provided in a JSON file rather than the standard YOLO format text files.
Attributes:
Name | Type | Description |
---|---|---|
json_file |
str
|
Path to the JSON file containing annotations. |
Methods:
Name | Description |
---|---|
get_img_files |
Return empty list as image files are read in get_labels. |
get_labels |
Load annotations from a JSON file and prepare them for training. |
build_transforms |
Configure augmentations for training with optional text loading. |
Examples:
>>> dataset = GroundingDataset(img_path="path/to/images", json_file="annotations.json", task="detect")
>>> len(dataset) # Number of valid images with annotations
Parameters:
Name | Type | Description | Default |
---|---|---|---|
json_file
|
str
|
Path to the JSON file containing annotations. |
''
|
task
|
str
|
Must be 'detect' or 'segment' for GroundingDataset. |
'detect'
|
*args
|
Any
|
Additional positional arguments for the parent class. |
()
|
**kwargs
|
Any
|
Additional keyword arguments for the parent class. |
{}
|
Source code in ultralytics/data/dataset.py
437 438 439 440 441 442 443 444 445 446 447 448 449 |
|
category_freq
property
category_freq
Return frequency of each category in the dataset.
category_names
property
category_names
Return unique category names from the dataset.
build_transforms
build_transforms(hyp: Optional[Dict] = None) -> Compose
Configure augmentations for training with optional text loading.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
hyp
|
dict
|
Hyperparameters for transforms. |
None
|
Returns:
Type | Description |
---|---|
Compose
|
Composed transforms including text augmentation if applicable. |
Source code in ultralytics/data/dataset.py
590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 |
|
cache_labels
cache_labels(path: Path = Path('./labels.cache')) -> Dict
Load annotations from a JSON file, filter, and normalize bounding boxes for each image.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
path
|
Path
|
Path where to save the cache file. |
Path('./labels.cache')
|
Returns:
Type | Description |
---|---|
dict
|
Dictionary containing cached labels and related information. |
Source code in ultralytics/data/dataset.py
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 |
|
get_img_files
get_img_files(img_path: str) -> List
The image files would be read in get_labels
function, return empty list here.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
img_path
|
str
|
Path to the directory containing images. |
required |
Returns:
Type | Description |
---|---|
list
|
Empty list as image files are read in get_labels. |
Source code in ultralytics/data/dataset.py
451 452 453 454 455 456 457 458 459 460 461 |
|
get_labels
get_labels() -> List[Dict]
Load labels from cache or generate them from JSON file.
Returns:
Type | Description |
---|---|
List[dict]
|
List of label dictionaries, each containing information about an image and its annotations. |
Source code in ultralytics/data/dataset.py
568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 |
|
verify_labels
verify_labels(labels: List[Dict]) -> None
Verify the number of instances in the dataset matches expected counts.
Source code in ultralytics/data/dataset.py
463 464 465 466 467 468 469 470 471 472 473 474 475 |
|
ultralytics.data.dataset.YOLOConcatDataset
Bases: ConcatDataset
Dataset as a concatenation of multiple datasets.
This class is useful to assemble different existing datasets for YOLO training, ensuring they use the same collation function.
Methods:
Name | Description |
---|---|
collate_fn |
Static method that collates data samples into batches using YOLODataset's collation function. |
Examples:
>>> dataset1 = YOLODataset(...)
>>> dataset2 = YOLODataset(...)
>>> combined_dataset = YOLOConcatDataset([dataset1, dataset2])
close_mosaic
close_mosaic(hyp: Dict) -> None
Set mosaic, copy_paste and mixup options to 0.0 and build transformations.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
hyp
|
dict
|
Hyperparameters for transforms. |
required |
Source code in ultralytics/data/dataset.py
665 666 667 668 669 670 671 672 673 674 675 |
|
collate_fn
staticmethod
collate_fn(batch: List[Dict]) -> Dict
Collate data samples into batches.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
batch
|
List[dict]
|
List of dictionaries containing sample data. |
required |
Returns:
Type | Description |
---|---|
dict
|
Collated batch with stacked tensors. |
Source code in ultralytics/data/dataset.py
652 653 654 655 656 657 658 659 660 661 662 663 |
|
ultralytics.data.dataset.SemanticDataset
SemanticDataset()
Bases: BaseDataset
Semantic Segmentation Dataset.
Source code in ultralytics/data/dataset.py
682 683 684 |
|
ultralytics.data.dataset.ClassificationDataset
ClassificationDataset(root: str, args, augment: bool = False, prefix: str = '')
Dataset class for image classification tasks extending torchvision ImageFolder functionality.
This class offers functionalities like image augmentation, caching, and verification. It's designed to efficiently handle large datasets for training deep learning models, with optional image transformations and caching mechanisms to speed up training.
Attributes:
Name | Type | Description |
---|---|---|
cache_ram |
bool
|
Indicates if caching in RAM is enabled. |
cache_disk |
bool
|
Indicates if caching on disk is enabled. |
samples |
list
|
A list of tuples, each containing the path to an image, its class index, path to its .npy cache file (if caching on disk), and optionally the loaded image array (if caching in RAM). |
torch_transforms |
callable
|
PyTorch transforms to be applied to the images. |
root |
str
|
Root directory of the dataset. |
prefix |
str
|
Prefix for logging and cache filenames. |
Methods:
Name | Description |
---|---|
__getitem__ |
Return subset of data and targets corresponding to given indices. |
__len__ |
Return the total number of samples in the dataset. |
verify_images |
Verify all images in dataset. |
Parameters:
Name | Type | Description | Default |
---|---|---|---|
root
|
str
|
Path to the dataset directory where images are stored in a class-specific folder structure. |
required |
args
|
Namespace
|
Configuration containing dataset-related settings such as image size, augmentation parameters, and cache settings. |
required |
augment
|
bool
|
Whether to apply augmentations to the dataset. |
False
|
prefix
|
str
|
Prefix for logging and cache filenames, aiding in dataset identification. |
''
|
Source code in ultralytics/data/dataset.py
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 |
|
__getitem__
__getitem__(i: int) -> Dict
Return subset of data and targets corresponding to given indices.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
i
|
int
|
Index of the sample to retrieve. |
required |
Returns:
Type | Description |
---|---|
dict
|
Dictionary containing the image and its class index. |
Source code in ultralytics/data/dataset.py
762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 |
|
__len__
__len__() -> int
Return the total number of samples in the dataset.
Source code in ultralytics/data/dataset.py
787 788 789 |
|
verify_images
verify_images() -> List[Tuple]
Verify all images in dataset.
Returns:
Type | Description |
---|---|
list
|
List of valid samples after verification. |
Source code in ultralytics/data/dataset.py
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 |
|