Reference for ultralytics/data/augment.py
Note
This file is available at https://github.com/ultralytics/ultralytics/blob/main/ultralytics/data/augment.py. If you spot a problem please help fix it by contributing a Pull Request 🛠️. Thank you 🙏!
ultralytics.data.augment.BaseTransform
Base class for image transformations.
This is a generic transformation class that can be extended for specific image processing needs. The class is designed to be compatible with both classification and semantic segmentation tasks.
Methods:
Name | Description |
---|---|
__init__ |
Initializes the BaseTransform object. |
apply_image |
Applies image transformation to labels. |
apply_instances |
Applies transformations to object instances in labels. |
apply_semantic |
Applies semantic segmentation to an image. |
__call__ |
Applies all label transformations to an image, instances, and semantic masks. |
Source code in ultralytics/data/augment.py
__call__(labels)
Applies all label transformations to an image, instances, and semantic masks.
__init__()
apply_image(labels)
apply_instances(labels)
ultralytics.data.augment.Compose
Class for composing multiple image transformations.
Source code in ultralytics/data/augment.py
__call__(data)
__getitem__(index)
Retrieve a specific transform or a set of transforms using indexing.
Source code in ultralytics/data/augment.py
__init__(transforms)
__repr__()
__setitem__(index, value)
Retrieve a specific transform or a set of transforms using indexing.
Source code in ultralytics/data/augment.py
append(transform)
insert(index, transform)
ultralytics.data.augment.BaseMixTransform
Class for base mix (MixUp/Mosaic) transformations.
This implementation is from mmyolo.
Source code in ultralytics/data/augment.py
__call__(labels)
Applies pre-processing transforms and mixup/mosaic transforms to labels data.
Source code in ultralytics/data/augment.py
__init__(dataset, pre_transform=None, p=0.0)
Initializes the BaseMixTransform object with dataset, pre_transform, and probability.
ultralytics.data.augment.Mosaic
Bases: BaseMixTransform
Mosaic augmentation.
This class performs mosaic augmentation by combining multiple (4 or 9) images into a single mosaic image. The augmentation is applied to a dataset with a given probability.
Attributes:
Name | Type | Description |
---|---|---|
dataset |
The dataset on which the mosaic augmentation is applied. |
|
imgsz |
int
|
Image size (height and width) after mosaic pipeline of a single image. Default to 640. |
p |
float
|
Probability of applying the mosaic augmentation. Must be in the range 0-1. Default to 1.0. |
n |
int
|
The grid size, either 4 (for 2x2) or 9 (for 3x3). |
Source code in ultralytics/data/augment.py
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 |
|
__init__(dataset, imgsz=640, p=1.0, n=4)
Initializes the object with a dataset, image size, probability, and border.
Source code in ultralytics/data/augment.py
get_indexes(buffer=True)
Return a list of random indexes from the dataset.
Source code in ultralytics/data/augment.py
ultralytics.data.augment.MixUp
Bases: BaseMixTransform
Class for applying MixUp augmentation to the dataset.
Source code in ultralytics/data/augment.py
__init__(dataset, pre_transform=None, p=0.0)
Initializes MixUp object with dataset, pre_transform, and probability of applying MixUp.
ultralytics.data.augment.RandomPerspective
Implements random perspective and affine transformations on images and corresponding bounding boxes, segments, and keypoints. These transformations include rotation, translation, scaling, and shearing. The class also offers the option to apply these transformations conditionally with a specified probability.
Attributes:
Name | Type | Description |
---|---|---|
degrees |
float
|
Degree range for random rotations. |
translate |
float
|
Fraction of total width and height for random translation. |
scale |
float
|
Scaling factor interval, e.g., a scale factor of 0.1 allows a resize between 90%-110%. |
shear |
float
|
Shear intensity (angle in degrees). |
perspective |
float
|
Perspective distortion factor. |
border |
tuple
|
Tuple specifying mosaic border. |
pre_transform |
callable
|
A function/transform to apply to the image before starting the random transformation. |
Methods:
Name | Description |
---|---|
affine_transform |
Applies a series of affine transformations to the image. |
apply_bboxes |
Transforms bounding boxes using the calculated affine matrix. |
apply_segments |
Transforms segments and generates new bounding boxes. |
apply_keypoints |
Transforms keypoints. |
__call__ |
Main method to apply transformations to both images and their corresponding annotations. |
box_candidates |
Filters out bounding boxes that don't meet certain criteria post-transformation. |
Source code in ultralytics/data/augment.py
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 |
|
__call__(labels)
Affine images and targets.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
labels |
dict
|
a dict of |
required |
Source code in ultralytics/data/augment.py
__init__(degrees=0.0, translate=0.1, scale=0.5, shear=0.0, perspective=0.0, border=(0, 0), pre_transform=None)
Initializes RandomPerspective object with transformation parameters.
Source code in ultralytics/data/augment.py
affine_transform(img, border)
Applies a sequence of affine transformations centered around the image center.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
img |
ndarray
|
Input image. |
required |
border |
tuple
|
Border dimensions. |
required |
Returns:
Name | Type | Description |
---|---|---|
img |
ndarray
|
Transformed image. |
M |
ndarray
|
Transformation matrix. |
s |
float
|
Scale factor. |
Source code in ultralytics/data/augment.py
apply_bboxes(bboxes, M)
Apply affine to bboxes only.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
bboxes |
ndarray
|
list of bboxes, xyxy format, with shape (num_bboxes, 4). |
required |
M |
ndarray
|
affine matrix. |
required |
Returns:
Name | Type | Description |
---|---|---|
new_bboxes |
ndarray
|
bboxes after affine, [num_bboxes, 4]. |
Source code in ultralytics/data/augment.py
apply_keypoints(keypoints, M)
Apply affine to keypoints.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
keypoints |
ndarray
|
keypoints, [N, 17, 3]. |
required |
M |
ndarray
|
affine matrix. |
required |
Returns:
Name | Type | Description |
---|---|---|
new_keypoints |
ndarray
|
keypoints after affine, [N, 17, 3]. |
Source code in ultralytics/data/augment.py
apply_segments(segments, M)
Apply affine to segments and generate new bboxes from segments.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
segments |
ndarray
|
list of segments, [num_samples, 500, 2]. |
required |
M |
ndarray
|
affine matrix. |
required |
Returns:
Name | Type | Description |
---|---|---|
new_segments |
ndarray
|
list of segments after affine, [num_samples, 500, 2]. |
new_bboxes |
ndarray
|
bboxes after affine, [N, 4]. |
Source code in ultralytics/data/augment.py
box_candidates(box1, box2, wh_thr=2, ar_thr=100, area_thr=0.1, eps=1e-16)
Compute box candidates based on a set of thresholds. This method compares the characteristics of the boxes before and after augmentation to decide whether a box is a candidate for further processing.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
box1 |
ndarray
|
The 4,n bounding box before augmentation, represented as [x1, y1, x2, y2]. |
required |
box2 |
ndarray
|
The 4,n bounding box after augmentation, represented as [x1, y1, x2, y2]. |
required |
wh_thr |
float
|
The width and height threshold in pixels. Default is 2. |
2
|
ar_thr |
float
|
The aspect ratio threshold. Default is 100. |
100
|
area_thr |
float
|
The area ratio threshold. Default is 0.1. |
0.1
|
eps |
float
|
A small epsilon value to prevent division by zero. Default is 1e-16. |
1e-16
|
Returns:
Type | Description |
---|---|
ndarray
|
A boolean array indicating which boxes are candidates based on the given thresholds. |
Source code in ultralytics/data/augment.py
ultralytics.data.augment.RandomHSV
This class is responsible for performing random adjustments to the Hue, Saturation, and Value (HSV) channels of an image.
The adjustments are random but within limits set by hgain, sgain, and vgain.
Source code in ultralytics/data/augment.py
__call__(labels)
Applies random HSV augmentation to an image within the predefined limits.
The modified image replaces the original image in the input 'labels' dict.
Source code in ultralytics/data/augment.py
__init__(hgain=0.5, sgain=0.5, vgain=0.5)
Initialize RandomHSV class with gains for each HSV channel.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
hgain |
float
|
Maximum variation for hue. Default is 0.5. |
0.5
|
sgain |
float
|
Maximum variation for saturation. Default is 0.5. |
0.5
|
vgain |
float
|
Maximum variation for value. Default is 0.5. |
0.5
|
Source code in ultralytics/data/augment.py
ultralytics.data.augment.RandomFlip
Applies a random horizontal or vertical flip to an image with a given probability.
Also updates any instances (bounding boxes, keypoints, etc.) accordingly.
Source code in ultralytics/data/augment.py
__call__(labels)
Applies random flip to an image and updates any instances like bounding boxes or keypoints accordingly.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
labels |
dict
|
A dictionary containing the keys 'img' and 'instances'. 'img' is the image to be flipped. 'instances' is an object containing bounding boxes and optionally keypoints. |
required |
Returns:
Type | Description |
---|---|
dict
|
The same dict with the flipped image and updated instances under the 'img' and 'instances' keys. |
Source code in ultralytics/data/augment.py
__init__(p=0.5, direction='horizontal', flip_idx=None)
Initializes the RandomFlip class with probability and direction.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
p |
float
|
The probability of applying the flip. Must be between 0 and 1. Default is 0.5. |
0.5
|
direction |
str
|
The direction to apply the flip. Must be 'horizontal' or 'vertical'. Default is 'horizontal'. |
'horizontal'
|
flip_idx |
array - like
|
Index mapping for flipping keypoints, if any. |
None
|
Source code in ultralytics/data/augment.py
ultralytics.data.augment.LetterBox
Resize image and padding for detection, instance segmentation, pose.
Source code in ultralytics/data/augment.py
__call__(labels=None, image=None)
Return updated labels and image with added border.
Source code in ultralytics/data/augment.py
__init__(new_shape=(640, 640), auto=False, scaleFill=False, scaleup=True, center=True, stride=32)
Initialize LetterBox object with specific parameters.
Source code in ultralytics/data/augment.py
ultralytics.data.augment.CopyPaste
Implements the Copy-Paste augmentation as described in the paper https://arxiv.org/abs/2012.07177. This class is responsible for applying the Copy-Paste augmentation on images and their corresponding instances.
Source code in ultralytics/data/augment.py
__call__(labels)
Applies the Copy-Paste augmentation to the given image and instances.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
labels |
dict
|
A dictionary containing: - 'img': The image to augment. - 'cls': Class labels associated with the instances. - 'instances': Object containing bounding boxes, and optionally, keypoints and segments. |
required |
Returns:
Type | Description |
---|---|
dict
|
Dict with augmented image and updated instances under the 'img', 'cls', and 'instances' keys. |
Notes
- Instances are expected to have 'segments' as one of their attributes for this augmentation to work.
- This method modifies the input dictionary 'labels' in place.
Source code in ultralytics/data/augment.py
__init__(p=0.5)
Initializes the CopyPaste class with a given probability.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
p |
float
|
The probability of applying the Copy-Paste augmentation. Must be between 0 and 1. Default is 0.5. |
0.5
|
Source code in ultralytics/data/augment.py
ultralytics.data.augment.Albumentations
Albumentations transformations.
Optional, uninstall package to disable. Applies Blur, Median Blur, convert to grayscale, Contrast Limited Adaptive Histogram Equalization, random change of brightness and contrast, RandomGamma and lowering of image quality by compression.
Source code in ultralytics/data/augment.py
__call__(labels)
Generates object detections and returns a dictionary with detection results.
Source code in ultralytics/data/augment.py
__init__(p=1.0)
Initialize the transform object for YOLO bbox formatted params.
Source code in ultralytics/data/augment.py
ultralytics.data.augment.Format
Formats image annotations for object detection, instance segmentation, and pose estimation tasks. The class
standardizes the image and instance annotations to be used by the collate_fn
in PyTorch DataLoader.
Attributes:
Name | Type | Description |
---|---|---|
bbox_format |
str
|
Format for bounding boxes. Default is 'xywh'. |
normalize |
bool
|
Whether to normalize bounding boxes. Default is True. |
return_mask |
bool
|
Return instance masks for segmentation. Default is False. |
return_keypoint |
bool
|
Return keypoints for pose estimation. Default is False. |
mask_ratio |
int
|
Downsample ratio for masks. Default is 4. |
mask_overlap |
bool
|
Whether to overlap masks. Default is True. |
batch_idx |
bool
|
Keep batch indexes. Default is True. |
bgr |
float
|
The probability to return BGR images. Default is 0.0. |
Source code in ultralytics/data/augment.py
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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 |
|
__call__(labels)
Return formatted image, classes, bounding boxes & keypoints to be used by 'collate_fn'.
Source code in ultralytics/data/augment.py
__init__(bbox_format='xywh', normalize=True, return_mask=False, return_keypoint=False, return_obb=False, mask_ratio=4, mask_overlap=True, batch_idx=True, bgr=0.0)
Initializes the Format class with given parameters.
Source code in ultralytics/data/augment.py
ultralytics.data.augment.RandomLoadText
Randomly sample positive texts and negative texts and update the class indices accordingly to the number of samples.
Attributes:
Name | Type | Description |
---|---|---|
prompt_format |
str
|
Format for prompt. Default is '{}'. |
neg_samples |
tuple[int]
|
A ranger to randomly sample negative texts, Default is (80, 80). |
max_samples |
int
|
The max number of different text samples in one image, Default is 80. |
padding |
bool
|
Whether to pad texts to max_samples. Default is False. |
padding_value |
str
|
The padding text. Default is "". |
Source code in ultralytics/data/augment.py
1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 |
|
__call__(labels)
Return updated classes and texts.
Source code in ultralytics/data/augment.py
__init__(prompt_format='{}', neg_samples=(80, 80), max_samples=80, padding=False, padding_value='')
Initializes the RandomLoadText class with given parameters.
Source code in ultralytics/data/augment.py
ultralytics.data.augment.ClassifyLetterBox
YOLOv8 LetterBox class for image preprocessing, designed to be part of a transformation pipeline, e.g., T.Compose([LetterBox(size), ToTensor()]).
Attributes:
Name | Type | Description |
---|---|---|
h |
int
|
Target height of the image. |
w |
int
|
Target width of the image. |
auto |
bool
|
If True, automatically solves for short side using stride. |
stride |
int
|
The stride value, used when 'auto' is True. |
Source code in ultralytics/data/augment.py
__call__(im)
Resizes the image and pads it with a letterbox method.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
im |
ndarray
|
The input image as a numpy array of shape HWC. |
required |
Returns:
Type | Description |
---|---|
ndarray
|
The letterboxed and resized image as a numpy array. |
Source code in ultralytics/data/augment.py
__init__(size=(640, 640), auto=False, stride=32)
Initializes the ClassifyLetterBox class with a target size, auto-flag, and stride.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
size |
Union[int, Tuple[int, int]]
|
The target dimensions (height, width) for the letterbox. |
(640, 640)
|
auto |
bool
|
If True, automatically calculates the short side based on stride. |
False
|
stride |
int
|
The stride value, used when 'auto' is True. |
32
|
Source code in ultralytics/data/augment.py
ultralytics.data.augment.CenterCrop
YOLOv8 CenterCrop class for image preprocessing, designed to be part of a transformation pipeline, e.g., T.Compose([CenterCrop(size), ToTensor()]).
Source code in ultralytics/data/augment.py
__call__(im)
Resizes and crops the center of the image using a letterbox method.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
im |
ndarray
|
The input image as a numpy array of shape HWC. |
required |
Returns:
Type | Description |
---|---|
ndarray
|
The center-cropped and resized image as a numpy array. |
Source code in ultralytics/data/augment.py
__init__(size=640)
ultralytics.data.augment.ToTensor
YOLOv8 ToTensor class for image preprocessing, i.e., T.Compose([LetterBox(size), ToTensor()]).
Source code in ultralytics/data/augment.py
__call__(im)
Transforms an image from a numpy array to a PyTorch tensor, applying optional half-precision and normalization.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
im |
ndarray
|
Input image as a numpy array with shape (H, W, C) in BGR order. |
required |
Returns:
Type | Description |
---|---|
Tensor
|
The transformed image as a PyTorch tensor in float32 or float16, normalized to [0, 1]. |
Source code in ultralytics/data/augment.py
__init__(half=False)
ultralytics.data.augment.v8_transforms(dataset, imgsz, hyp, stretch=False)
Convert images to a size suitable for YOLOv8 training.
Source code in ultralytics/data/augment.py
ultralytics.data.augment.classify_transforms(size=224, mean=DEFAULT_MEAN, std=DEFAULT_STD, interpolation=Image.BILINEAR, crop_fraction=DEFAULT_CROP_FRACTION)
Classification transforms for evaluation/inference. Inspired by timm/data/transforms_factory.py.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
size |
int
|
image size |
224
|
mean |
tuple
|
mean values of RGB channels |
DEFAULT_MEAN
|
std |
tuple
|
std values of RGB channels |
DEFAULT_STD
|
interpolation |
InterpolationMode
|
interpolation mode. default is T.InterpolationMode.BILINEAR. |
BILINEAR
|
crop_fraction |
float
|
fraction of image to crop. default is 1.0. |
DEFAULT_CROP_FRACTION
|
Returns:
Type | Description |
---|---|
Compose
|
torchvision transforms |
Source code in ultralytics/data/augment.py
ultralytics.data.augment.classify_augmentations(size=224, mean=DEFAULT_MEAN, std=DEFAULT_STD, scale=None, ratio=None, hflip=0.5, vflip=0.0, auto_augment=None, hsv_h=0.015, hsv_s=0.4, hsv_v=0.4, force_color_jitter=False, erasing=0.0, interpolation=Image.BILINEAR)
Classification transforms with augmentation for training. Inspired by timm/data/transforms_factory.py.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
size |
int
|
image size |
224
|
scale |
tuple
|
scale range of the image. default is (0.08, 1.0) |
None
|
ratio |
tuple
|
aspect ratio range of the image. default is (3./4., 4./3.) |
None
|
mean |
tuple
|
mean values of RGB channels |
DEFAULT_MEAN
|
std |
tuple
|
std values of RGB channels |
DEFAULT_STD
|
hflip |
float
|
probability of horizontal flip |
0.5
|
vflip |
float
|
probability of vertical flip |
0.0
|
auto_augment |
str
|
auto augmentation policy. can be 'randaugment', 'augmix', 'autoaugment' or None. |
None
|
hsv_h |
float
|
image HSV-Hue augmentation (fraction) |
0.015
|
hsv_s |
float
|
image HSV-Saturation augmentation (fraction) |
0.4
|
hsv_v |
float
|
image HSV-Value augmentation (fraction) |
0.4
|
force_color_jitter |
bool
|
force to apply color jitter even if auto augment is enabled |
False
|
erasing |
float
|
probability of random erasing |
0.0
|
interpolation |
InterpolationMode
|
interpolation mode. default is T.InterpolationMode.BILINEAR. |
BILINEAR
|
Returns:
Type | Description |
---|---|
Compose
|
torchvision transforms |
Source code in ultralytics/data/augment.py
1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 |
|