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
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 |
Returns dictionary of labels for YOLO training. |
build_transforms |
Builds and appends transforms to the list. |
close_mosaic |
Sets mosaic, copy_paste and mixup options to 0.0 and builds transformations. |
update_labels_info |
Updates label format for different tasks. |
collate_fn |
Collates 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
build_transforms
Builds and appends 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
cache_labels
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
close_mosaic
Sets mosaic, copy_paste and mixup options to 0.0 and builds transformations.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
hyp
|
dict
|
Hyperparameters for transforms. |
required |
Source code in ultralytics/data/dataset.py
collate_fn
staticmethod
Collates 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
get_labels
Returns 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
update_labels_info
Custom your label format here.
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
ultralytics.data.dataset.YOLOMultiModalDataset
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 |
Adds text information for multi-modal model training. |
build_transforms |
Enhances 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
category_names
property
Return category names for the dataset.
Returns:
Type | Description |
---|---|
Tuple[str]
|
List of class names. |
build_transforms
Enhances 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
update_labels_info
Add texts 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
ultralytics.data.dataset.GroundingDataset
Bases: YOLODataset
Handles object detection tasks by loading annotations from a specified JSON file, supporting YOLO 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 |
Returns empty list as image files are read in get_labels. |
get_labels |
Loads annotations from a JSON file and prepares them for training. |
build_transforms |
Configures 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
build_transforms
Configures 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
cache_labels
Loads annotations from a JSON file, filters, and normalizes 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
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 |
|
get_img_files
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
get_labels
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
verify_labels
Verify the number of instances in the dataset matches expected counts.
Source code in ultralytics/data/dataset.py
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
Sets mosaic, copy_paste and mixup options to 0.0 and builds transformations.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
hyp
|
dict
|
Hyperparameters for transforms. |
required |
Source code in ultralytics/data/dataset.py
collate_fn
staticmethod
Collates 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
ultralytics.data.dataset.SemanticDataset
ultralytics.data.dataset.ClassificationDataset
Extends torchvision ImageFolder to support YOLO classification tasks.
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__ |
Returns subset of data and targets corresponding to given indices. |
__len__ |
Returns the total number of samples in the dataset. |
verify_images |
Verifies 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
__getitem__
Returns 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
__len__
verify_images
Verify all images in dataset.
Returns:
Type | Description |
---|---|
list
|
List of valid samples after verification. |