Datasets
RandAugment RandAugment is a variant of AutoAugment which randomly selects transformations from AutoAugment to be applied on an image.
RandomAugmentation Implementation adapted from: https://github.com/rwightman/pytorch-image-models/blob/master/timm/data/auto_augment.py
Papers: RandAugment: Practical automated data augmentation... - https://arxiv.org/abs/1909.13719
AugmentOp
single auto augment operations
Source code in training/datasets/auto_augment.py
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 |
|
RandAugment
Random auto augment class, will select auto augment transforms according to probability weights for each op
Source code in training/datasets/auto_augment.py
380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 |
|
rand_augment_transform(config_str, crop_size, img_mean)
Create a RandAugment transform
Parameters:
Name | Type | Description | Default |
---|---|---|---|
config_str |
String defining configuration of random augmentation. Consists of multiple sections separated by dashes ('-'). The first section defines the specific variant of rand augment (currently only 'rand'). The remaining sections, not order sepecific determine 'm' - integer magnitude of rand augment 'n' - integer num layers (number of transform ops selected per image) 'w' - integer probabiliy weight index (index of a set of weights to influence choice of op) 'mstd' - float std deviation of magnitude noise applied 'inc' - integer (bool), use augmentations that increase in severity with magnitude (default: 0) Ex 'rand-m9-n3-mstd0.5' results in RandAugment with magnitude 9, num_layers 3, magnitude_std 0.5 'rand-mstd1-w0' results in magnitude_std 1.0, weights 0, default magnitude of 10 and num_layers 2 |
required | |
crop_size |
int
|
The size of crop image |
required |
img_mean |
List[float]
|
Average per channel |
required |
Returns:
Type | Description |
---|---|
A PyTorch compatible Transform |
Source code in training/datasets/auto_augment.py
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 |
|
Cifar10
Bases: CIFAR10
CIFAR10 Dataset
Parameters:
Name | Type | Description | Default |
---|---|---|---|
root |
str
|
Path for the data to be extracted |
required |
train |
bool
|
Bool to load training (True) or validation (False) part of the dataset |
True
|
transforms |
Union[list, dict]
|
List of transforms to apply sequentially on sample. Wrapped internally with torchvision.Compose |
None
|
target_transform |
Optional[Callable]
|
Transform to apply to target output |
None
|
download |
bool
|
Download (True) the dataset from source |
False
|
Source code in training/datasets/classification_datasets/cifar.py
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
|
Cifar100
Bases: CIFAR100
Source code in training/datasets/classification_datasets/cifar.py
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 |
|
__init__(root, train=True, transforms=None, target_transform=None, download=False)
CIFAR100 Dataset
Parameters:
Name | Type | Description | Default |
---|---|---|---|
root |
str
|
Path for the data to be extracted |
required |
train |
bool
|
Bool to load training (True) or validation (False) part of the dataset |
True
|
transforms |
Union[list, dict]
|
List of transforms to apply sequentially on sample. Wrapped internally with torchvision.Compose |
None
|
target_transform |
Optional[Callable]
|
Transform to apply to target output |
None
|
download |
bool
|
Download (True) the dataset from source |
False
|
Source code in training/datasets/classification_datasets/cifar.py
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 |
|
ImageNetDataset
Bases: torch_datasets.ImageFolder
ImageNetDataset dataset.
To use this Dataset you need to:
-
Download imagenet dataset (https://image-net.org/download.php) Imagenet ├──train │ ├──n02093991 │ │ ├──n02093991_1001.JPEG │ │ ├──n02093991_1004.JPEG │ │ └──... │ ├──n02093992 │ └──... └──val ├──n02093991 ├──n02093992 └──...
-
Instantiate the dataset: >> train_set = ImageNetDataset(root='.../Imagenet/train', ...) >> valid_set = ImageNetDataset(root='.../Imagenet/val', ...)
Source code in training/datasets/classification_datasets/imagenet_dataset.py
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
|
Lighting
Bases: object
Lighting noise(AlexNet - style PCA - based noise) Taken from fastai Imagenet training - https://github.com/fastai/imagenet-fast/blob/faa0f9dfc9e8e058ffd07a248724bf384f526fae/imagenet_nv/fastai_imagenet.py#L103 To use: - training_params = {"imagenet_pca_aug": 0.1} - Default training_params arg is 0.0 ("don't use") - 0.1 is that default in the original paper
Source code in training/datasets/data_augmentation.py
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 |
|
RandomErase
Bases: RandomErasing
A simple class that translates the parameters supported in SuperGradient's code base
Source code in training/datasets/data_augmentation.py
99 100 101 102 103 104 105 106 107 108 109 110 111 112 |
|
BoundingBoxFormat
Abstract class for describing a bounding boxes format. It exposes two methods: to_xyxy and from_xyxy to convert whatever format of boxes we are dealing with to internal xyxy format and vice versa. This conversion from and to intermediate xyxy format has a subtle performance impact, but greatly reduce amount of boilerplate code to support all combinations of conversion xyxy, xywh, cxcywh, yxyx <-> xyxy, xywh, cxcywh, yxyx.
Source code in training/datasets/data_formats/bbox_formats/bbox_format.py
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
|
from_xyxy(bboxes, image_shape, inplace)
Convert XYXY boxes to target bboxes format
Parameters:
Name | Type | Description | Default |
---|---|---|---|
bboxes |
Input bounding boxes [..., 4] in XYXY format |
required | |
image_shape |
Tuple[int, int]
|
Dimensions (rows, cols) of the original image to support normalized boxes or non top-left origin coordinate system. |
required |
Returns:
Type | Description |
---|---|
Converted bounding boxes [..., 4] in target format |
Source code in training/datasets/data_formats/bbox_formats/bbox_format.py
27 28 29 30 31 32 33 34 35 |
|
to_xyxy(bboxes, image_shape, inplace)
Convert input boxes to XYXY format
Parameters:
Name | Type | Description | Default |
---|---|---|---|
bboxes |
Input bounding boxes [..., 4] |
required | |
image_shape |
Tuple[int, int]
|
Dimensions (rows, cols) of the original image to support normalized boxes or non top-left origin coordinate system. |
required |
Returns:
Type | Description |
---|---|
Converted bounding boxes [..., 4] in XYXY format |
Source code in training/datasets/data_formats/bbox_formats/bbox_format.py
17 18 19 20 21 22 23 24 25 |
|
convert_bboxes(bboxes, image_shape, source_format, target_format, inplace)
Convert bboxes from source to target format
Parameters:
Name | Type | Description | Default |
---|---|---|---|
bboxes |
Tensor of shape (..., 4) with input bounding boxes |
required | |
image_shape |
Tuple[int, int]
|
Tuple of (rows, cols) corresponding to image shape |
required |
source_format |
BoundingBoxFormat
|
Format of the source bounding boxes |
required |
target_format |
BoundingBoxFormat
|
Format of the output bounding boxes |
required |
Returns:
Type | Description |
---|---|
Tensor of shape (..., 4) with resulting bounding boxes |
Source code in training/datasets/data_formats/bbox_formats/bbox_format.py
49 50 51 52 53 54 55 56 57 58 59 |
|
cxcywh_to_xyxy(bboxes, image_shape)
Transforms bboxes from CX-CY-W-H format to XYXY format
Parameters:
Name | Type | Description | Default |
---|---|---|---|
bboxes |
BBoxes of shape (..., 4) in CX-CY-W-H format |
required |
Returns:
Type | Description |
---|---|
BBoxes of shape (..., 4) in XYXY format |
Source code in training/datasets/data_formats/bbox_formats/cxcywh.py
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
|
cxcywh_to_xyxy_inplace(bboxes, image_shape)
Not that bboxes dtype is preserved, and it may lead to unwanted rounding errors when computing a center of bbox.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
bboxes |
BBoxes of shape (..., 4) in CX-CY-W-H format |
required |
Returns:
Type | Description |
---|---|
BBoxes of shape (..., 4) in XYXY format |
Source code in training/datasets/data_formats/bbox_formats/cxcywh.py
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 |
|
xyxy_to_cxcywh(bboxes, image_shape)
Transforms bboxes from xyxy format to CX-CY-W-H format
Parameters:
Name | Type | Description | Default |
---|---|---|---|
bboxes |
BBoxes of shape (..., 4) in XYXY format |
required |
Returns:
Type | Description |
---|---|
BBoxes of shape (..., 4) in CX-CY-W-H format |
Source code in training/datasets/data_formats/bbox_formats/cxcywh.py
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
|
xyxy_to_cxcywh_inplace(bboxes, image_shape)
Transforms bboxes from xyxy format to CX-CY-W-H format. This function operates in-place. Not that bboxes dtype is preserved, and it may lead to unwanted rounding errors when computing a center of bbox.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
bboxes |
BBoxes of shape (..., 4) in XYXY format |
required |
Returns:
Type | Description |
---|---|
BBoxes of shape (..., 4) in CX-CY-W-H format |
Source code in training/datasets/data_formats/bbox_formats/cxcywh.py
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 |
|
NormalizedXYXYCoordinateFormat
Bases: BoundingBoxFormat
Normalized X1,Y1,X2,Y2 bounding boxes format
Source code in training/datasets/data_formats/bbox_formats/normalized_xyxy.py
106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 |
|
normalized_xyxy_to_xyxy(bboxes, image_shape)
Convert unit-normalized XYXY bboxes to XYXY bboxes in pixel units.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
bboxes |
BBoxes of shape (..., 4) in XYXY (unit-normalized) format |
required | |
image_shape |
Tuple[int, int]
|
Image shape (rows,cols) |
required |
Returns:
Type | Description |
---|---|
BBoxes of shape (..., 4) in XYXY (pixels) format |
Source code in training/datasets/data_formats/bbox_formats/normalized_xyxy.py
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
|
normalized_xyxy_to_xyxy_inplace(bboxes, image_shape)
Convert unit-normalized XYXY bboxes to XYXY bboxes in pixel units. This function operates in-place.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
bboxes |
BBoxes of shape (..., 4) in XYXY (unit-normalized) format |
required | |
image_shape |
Tuple[int, int]
|
Image shape (rows,cols) |
required |
Returns:
Type | Description |
---|---|
BBoxes of shape (..., 4) in XYXY (pixels) format |
Source code in training/datasets/data_formats/bbox_formats/normalized_xyxy.py
67 68 69 70 71 72 73 74 75 76 77 |
|
xyxy_to_normalized_xyxy(bboxes, image_shape)
Convert bboxes from XYXY (pixels) format to XYXY (unit-normalized) format
Parameters:
Name | Type | Description | Default |
---|---|---|---|
bboxes |
Tensor
|
BBoxes of shape (..., 4) in XYXY (pixels) format |
required |
image_shape |
Tuple[int, int]
|
Image shape (rows,cols) |
required |
Returns:
Type | Description |
---|---|
Tensor
|
BBoxes of shape (..., 4) in XYXY (unit-normalized) format |
Source code in training/datasets/data_formats/bbox_formats/normalized_xyxy.py
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 |
|
xyxy_to_normalized_xyxy_inplace(bboxes, image_shape)
Convert bboxes from XYXY (pixels) format to XYXY (unit-normalized) format. This function operates in-place.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
bboxes |
BBoxes of shape (..., 4) in XYXY (pixels) format |
required | |
image_shape |
Tuple[int, int]
|
Image shape (rows,cols) |
required |
Returns:
Type | Description |
---|---|
BBoxes of shape (..., 4) in XYXY (unit-normalized) format |
Source code in training/datasets/data_formats/bbox_formats/normalized_xyxy.py
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 |
|
xywh_to_xyxy(bboxes, image_shape)
Transforms bboxes from XYWH format to XYXY format
Parameters:
Name | Type | Description | Default |
---|---|---|---|
bboxes |
BBoxes of shape (..., 4) in XYWH format |
required |
Returns:
Type | Description |
---|---|
BBoxes of shape (..., 4) in XYXY format |
Source code in training/datasets/data_formats/bbox_formats/xywh.py
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
|
xywh_to_xyxy_inplace(bboxes, image_shape)
Transforms bboxes from XYWH format to XYXY format
Parameters:
Name | Type | Description | Default |
---|---|---|---|
bboxes |
BBoxes of shape (..., 4) in XYWH format |
required |
Returns:
Type | Description |
---|---|
BBoxes of shape (..., 4) in XYXY format |
Source code in training/datasets/data_formats/bbox_formats/xywh.py
65 66 67 68 69 70 71 72 |
|
xyxy_to_xywh(bboxes, image_shape)
Transforms bboxes inplace from XYXY format to XYWH format
Parameters:
Name | Type | Description | Default |
---|---|---|---|
bboxes |
BBoxes of shape (..., 4) in XYXY format |
required |
Returns:
Type | Description |
---|---|
BBoxes of shape (..., 4) in XYWH format |
Source code in training/datasets/data_formats/bbox_formats/xywh.py
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
|
xyxy_to_xywh_inplace(bboxes, image_shape)
Transforms bboxes inplace from XYXY format to XYWH format. This function operates in-place.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
bboxes |
BBoxes of shape (..., 4) in XYXY format |
required |
Returns:
Type | Description |
---|---|
BBoxes of shape (..., 4) in XYWH format |
Source code in training/datasets/data_formats/bbox_formats/xywh.py
55 56 57 58 59 60 61 62 |
|
XYXYCoordinateFormat
Bases: BoundingBoxFormat
Bounding boxes format X1, Y1, X2, Y2
Source code in training/datasets/data_formats/bbox_formats/xyxy.py
14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
|
YXYXCoordinateFormat
Bases: BoundingBoxFormat
Bounding boxes format Y1, X1, Y2, X1
Source code in training/datasets/data_formats/bbox_formats/yxyx.py
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
|
ConcatenatedTensorFormatConverter
Source code in training/datasets/data_formats/format_converter.py
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 |
|
__init__(input_format, output_format, image_shape)
Converts concatenated tensors from input format to output format.
Example: >>> from super_gradients.training.datasets.data_formats import ConcatenatedTensorFormatConverter >>> from super_gradients.training.datasets.data_formats.default_formats import LABEL_CXCYWH, LABEL_NORMALIZED_XYXY >>> h, w = 100, 200 >>> input_target = np.array([[10, 20 / w, 30 / h, 40 / w, 50 / h]], dtype=np.float32) >>> expected_output_target = np.array([[10, 30, 40, 20, 20]], dtype=np.float32) >>> >>> transform = ConcatenatedTensorFormatConverter(input_format=LABEL_NORMALIZED_XYXY, output_format=LABEL_CXCYWH, image_shape=(h, w)) >>> >>> # np.float32 approximation of multiplication/division can lead to uncertainty of up to 1e-7 in precision >>> assert np.allclose(transform(input_target), expected_output_target, atol=1e-6)
Parameters:
Name | Type | Description | Default |
---|---|---|---|
input_format |
ConcatenatedTensorFormat
|
Format definition of the inputs |
required |
output_format |
ConcatenatedTensorFormat
|
Format definition of the outputs |
required |
image_shape |
Union[Tuple[int, int], None]
|
Shape of the input image (rows, cols), used for converting bbox coordinates from/to normalized format. If you're not using normalized coordinates you can set this to None |
required |
Source code in training/datasets/data_formats/format_converter.py
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
|
ConcatenatedTensorFormat
Bases: DetectionOutputFormat
Define the output format that return a single tensor of shape [N,M] (N - number of detections, M - sum of bbox attributes) that is a concatenated from bbox coordinates and other fields. A layout defines the order of concatenated tensors. For instance: - layout: (bboxes, scores, labels) gives a Tensor that is product of torch.cat([bboxes, scores, labels], dim=1) - layout: (labels, bboxes) produce a Tensor from torch.cat([labels, bboxes], dim=1)
from super_gradients.training.datasets.data_formats.formats import ConcatenatedTensorFormat, BoundingBoxesTensorSliceItem, TensorSliceItem from super_gradients.training.datasets.data_formats.bbox_formats import XYXYCoordinateFormat, NormalizedXYWHCoordinateFormat
custom_format = ConcatenatedTensorFormat( layout=( BoundingBoxesTensorSliceItem(name="bboxes", format=XYXYCoordinateFormat()), TensorSliceItem(name="label", length=1), TensorSliceItem(name="distance", length=1), TensorSliceItem(name="attributes", length=4), ) )
Source code in training/datasets/data_formats/formats.py
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 |
|
apply_on_bboxes(fn, tensor, tensor_format)
Apply inplace a function only on the bboxes of a concatenated tensor.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
fn |
Callable[[Union[np.ndarray, Tensor]], Union[np.ndarray, Tensor]]
|
Function to apply on the bboxes. |
required |
tensor |
Union[np.ndarray, Tensor]
|
Concatenated tensor that include - among other - the bboxes. |
required |
tensor_format |
ConcatenatedTensorFormat
|
Format of the tensor, required to know the indexes of the bboxes. |
required |
Returns:
Type | Description |
---|---|
Union[np.ndarray, Tensor]
|
Tensor, after applying INPLACE the fn on the bboxes |
Source code in training/datasets/data_formats/formats.py
98 99 100 101 102 103 104 105 106 107 108 109 110 |
|
apply_on_layout(fn, tensor, tensor_format, layout_name)
Apply inplace a function only on a specific layout of a concatenated tensor.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
fn |
Callable[[Union[np.ndarray, Tensor]], Union[np.ndarray, Tensor]]
|
Function to apply on the bboxes. |
required |
tensor |
Union[np.ndarray, Tensor]
|
Concatenated tensor that include - among other - the layout of interest. |
required |
tensor_format |
ConcatenatedTensorFormat
|
Format of the tensor, required to know the indexes of the layout. |
required |
layout_name |
str
|
Name of the layout of interest. It has to be defined in the tensor_format. |
required |
Returns:
Type | Description |
---|---|
Union[np.ndarray, Tensor]
|
Tensor, after applying INPLACE the fn on the layout |
Source code in training/datasets/data_formats/formats.py
113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 |
|
filter_on_bboxes(fn, tensor, tensor_format)
Filter the tensor according to a condition on the bboxes.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
fn |
Callable[[Union[np.ndarray, Tensor]], Union[np.ndarray, Tensor]]
|
Function to filter the bboxes (keep only True elements). |
required |
tensor |
Union[np.ndarray, Tensor]
|
Concatenated tensor that include - among other - the bboxes. |
required |
tensor_format |
ConcatenatedTensorFormat
|
Format of the tensor, required to know the indexes of the bboxes. |
required |
Returns:
Type | Description |
---|---|
Union[np.ndarray, Tensor]
|
Tensor, after applying INPLACE the fn on the bboxes |
Source code in training/datasets/data_formats/formats.py
132 133 134 135 136 137 138 139 140 141 142 143 144 |
|
filter_on_layout(fn, tensor, tensor_format, layout_name)
Filter the tensor according to a condition on a specific layout.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
fn |
Callable[[Union[np.ndarray, Tensor]], Union[np.ndarray, Tensor]]
|
Function to filter the bboxes (keep only True elements). |
required |
tensor |
Union[np.ndarray, Tensor]
|
Concatenated tensor that include - among other - the layout of interest. |
required |
tensor_format |
ConcatenatedTensorFormat
|
Format of the tensor, required to know the indexes of the layout. |
required |
layout_name |
str
|
Name of the layout of interest. It has to be defined in the tensor_format. |
required |
Returns:
Type | Description |
---|---|
Union[np.ndarray, Tensor]
|
Tensor, after filtering the bboxes according to fn. |
Source code in training/datasets/data_formats/formats.py
147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 |
|
get_permutation_indexes(input_format, output_format)
Compute the permutations required to change the format layout order.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
input_format |
ConcatenatedTensorFormat
|
Input format to transform from |
required |
output_format |
ConcatenatedTensorFormat
|
Output format to transform to |
required |
Returns:
Type | Description |
---|---|
List[int]
|
Permutation indexes to go from input to output format. |
Source code in training/datasets/data_formats/formats.py
167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 |
|
ConvertBoundingBoxes
Bases: nn.Module
Source code in training/datasets/data_formats/output_adapters/detection_adapter.py
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 |
|
forward(x)
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x |
Tensor
|
required | |
image_shape |
required |
Returns:
Type | Description |
---|---|
Tensor
|
Source code in training/datasets/data_formats/output_adapters/detection_adapter.py
56 57 58 59 60 61 62 63 64 65 66 67 |
|
DetectionOutputAdapter
Bases: nn.Module
Adapter class for converting model's predictions for object detection to a desired format. This adapter supports torch.jit tracing & scripting & onnx conversion.
from super_gradients.training.datasets.data_formats.formats import ConcatenatedTensorFormat, BoundingBoxesTensorSliceItem, TensorSliceItem from super_gradients.training.datasets.data_formats.bbox_formats import XYXYCoordinateFormat, NormalizedXYWHCoordinateFormat
class CustomDetectionHead(nn.Module): num_classes: int = 123
@property def format(self): ''' Describe the semantics of the model's output. In this example model's output consists of - Bounding boxes in XYXY format [4] - Predicted probas of N classes [N] - A distance predictions [1] - K additional labels [K] ''' return ConcatenatedTensorFormat( layout=( BoundingBoxesTensorSliceItem(name="bboxes", format=XYXYCoordinateFormat()), TensorSliceItem(name="label", length=1), TensorSliceItem(name="distance", length=1), TensorSliceItem(name="attributes", length=4), ) )
yolox = YoloX(head=CustomDetectionHead)
Suppose we want to return predictions in another format.
Let it be:
- Bounding boxes in normalized XYWH [4]
- Predicted attributes [4]
- Predicted label [1]
output_format = ConcatenatedTensorFormat( layout=( # Note: For output format it is not required to specify location attribute as it will be # computed with respect to size of "source name" and order of items in layout describe their order in the output tensor BoundingBoxesTensorSliceItem(name="bboxes", format=NormalizedXYWHCoordinateFormat()), TensorSliceItem(name="attributes", length=4), TensorSliceItem(name="label", length=1), ) )
Now we can construct output adapter and attach it to the model
output_adapter = DetectionOutputAdapter( input_format=yolox.head.format, output_format=output_format, image_shape=(640, 640) )
yolox = nn.Sequential(yolox, output_adapter)
Source code in training/datasets/data_formats/output_adapters/detection_adapter.py
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 |
|
__init__(input_format, output_format, image_shape)
Parameters:
Name | Type | Description | Default |
---|---|---|---|
input_format |
ConcatenatedTensorFormat
|
Format definition of the inputs |
required |
output_format |
ConcatenatedTensorFormat
|
Format definition of the outputs |
required |
image_shape |
Union[Tuple[int, int], None]
|
Shape of the input image (rows, cols), used for converting bbox coordinates from/to normalized format. If you're not using normalized coordinates you can set this to None |
required |
Source code in training/datasets/data_formats/output_adapters/detection_adapter.py
127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 |
|
forward(predictions)
Convert output detections to the user-specified format
Parameters:
Name | Type | Description | Default |
---|---|---|---|
predictions |
Tensor
|
required |
Returns:
Type | Description |
---|---|
Tensor
|
Source code in training/datasets/data_formats/output_adapters/detection_adapter.py
150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 |
|
RearrangeOutput
Bases: nn.Module
Rearrange elements in last dimension of input tensor with respect to index argument
Source code in training/datasets/data_formats/output_adapters/detection_adapter.py
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
|
forward(x)
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x |
Tensor
|
Input tensor of [..., N] shape |
required |
Returns:
Type | Description |
---|---|
Tensor
|
Output tensor of [..., N[index]] shape |
Source code in training/datasets/data_formats/output_adapters/detection_adapter.py
23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
|
AbstractCollateFunction
Bases: ABC
A collate function (for torch DataLoader)
Source code in training/datasets/datasets_utils.py
76 77 78 79 80 81 82 83 |
|
AbstractPrePredictionCallback
Bases: ABC
Abstract class for forward pass preprocessing function, to be used by passing its inheritors through training_params pre_prediction_callback keyword arg.
Should implement call and return images, targets after applying the desired preprocessing.
Source code in training/datasets/datasets_utils.py
175 176 177 178 179 180 181 182 183 184 185 |
|
ComposedCollateFunction
Bases: AbstractCollateFunction
A function (for torch DataLoader) which executes a sequence of sub collate functions
Source code in training/datasets/datasets_utils.py
86 87 88 89 90 91 92 93 94 95 96 97 98 |
|
DatasetStatisticsTensorboardLogger
Source code in training/datasets/datasets_utils.py
371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 |
|
analyze(data_loader, title, all_classes, anchors=None)
Parameters:
Name | Type | Description | Default |
---|---|---|---|
data_loader |
torch.utils.data.DataLoader
|
the dataset data loader |
required |
dataset_params |
the dataset parameters |
required | |
title |
str
|
the title for this dataset (i.e. Coco 2017 test set) |
required |
anchors |
list
|
the list of anchors used by the model. applicable only for detection datasets |
None
|
all_classes |
List[str]
|
the list of all classes names |
required |
Source code in training/datasets/datasets_utils.py
386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 |
|
DetectionMultiscalePrePredictionCallback
Bases: MultiscalePrePredictionCallback
Mutiscalepre-prediction callback for object detection.
When passed through train_params images, targets will be applied by the below transform to support multi scaling on the fly.
After each self.frequency forward passes, change size randomly from (input_size-self.multiscale_rangeself.image_size_steps, input_size-(self.multiscale_range-1)self.image_size_steps, ...input_size+self.multiscale_range*self.image_size_steps) and apply the same rescaling to the box coordinates.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
multiscale_range |
Range of values for resize sizes as discussed above (default=5) |
required | |
image_size_steps |
Image step sizes as discussed abov (default=32) |
required | |
change_frequency |
The frequency to apply change in input size. |
required |
Source code in training/datasets/datasets_utils.py
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 |
|
MultiScaleCollateFunction
Bases: AbstractCollateFunction
a collate function to implement multi-scale data augmentation according to https://arxiv.org/pdf/1612.08242.pdf
Source code in training/datasets/datasets_utils.py
112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 |
|
__init__(target_size=None, min_image_size=None, max_image_size=None, image_size_steps=32, change_frequency=10)
set parameters for the multi-scale collate function the possible image sizes are in range [min_image_size, max_image_size] in steps of image_size_steps a new size will be randomly selected every change_frequency calls to the collate_fn() :param target_size: scales will be [0.66 * target_size, 1.5 * target_size] :param min_image_size: the minimum size to scale down to (in pixels) :param max_image_size: the maximum size to scale up to (in pixels) :param image_size_steps: typically, the stride of the net, which defines the possible image size multiplications :param change_frequency:
Source code in training/datasets/datasets_utils.py
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 |
|
MultiscalePrePredictionCallback
Bases: AbstractPrePredictionCallback
Mutiscale pre-prediction callback pass function.
When passed through train_params images, targets will be applied by the below transform to support multi scaling on the fly.
After each self.frequency forward passes, change size randomly from (input_size-self.multiscale_rangeself.image_size_steps, input_size-(self.multiscale_range-1)self.image_size_steps, ...input_size+self.multiscale_range*self.image_size_steps)
Parameters:
Name | Type | Description | Default |
---|---|---|---|
multiscale_range |
int
|
Range of values for resize sizes as discussed above (default=5) |
5
|
image_size_steps |
int
|
Image step sizes as discussed abov (default=32) |
32
|
change_frequency |
int
|
The frequency to apply change in input size. |
10
|
Source code in training/datasets/datasets_utils.py
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 |
|
RandomResizedCropAndInterpolation
Bases: RandomResizedCrop
Crop the given PIL Image to random size and aspect ratio with explicitly chosen or random interpolation.
A crop of random size (default: of 0.08 to 1.0) of the original size and a random aspect ratio (default: of 3/4 to 4/3) of the original aspect ratio is made. This crop is finally resized to given size. This is popularly used to train the Inception networks.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
size |
Expected output size of each edge |
required | |
scale |
Range of size of the origin size cropped |
(0.08, 1.0)
|
|
ratio |
Range of aspect ratio of the origin aspect ratio cropped |
(3.0 / 4.0, 4.0 / 3.0)
|
|
interpolation |
Default: PIL.Image.BILINEAR |
'default'
|
Source code in training/datasets/datasets_utils.py
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 |
|
forward(img)
Parameters:
Name | Type | Description | Default |
---|---|---|---|
img |
Image
|
Image to be cropped and resized. |
required |
Returns:
Type | Description |
---|---|
Image
|
Image: Randomly cropped and resized image. |
Source code in training/datasets/datasets_utils.py
344 345 346 347 348 349 350 351 352 353 354 |
|
get_color_augmentation(rand_augment_config_string, color_jitter, crop_size=224, img_mean=[0.485, 0.456, 0.406])
Returns color augmentation class. As these augmentation cannot work on top one another, only one is returned according to rand_augment_config_string
Parameters:
Name | Type | Description | Default |
---|---|---|---|
rand_augment_config_string |
str
|
string which defines the auto augment configurations. If none, color jitter will be returned. For possibile values see auto_augment.py |
required |
color_jitter |
tuple
|
tuple for color jitter value. |
required |
crop_size |
relevant only for auto augment |
224
|
|
img_mean |
relevant only for auto augment |
[0.485, 0.456, 0.406]
|
Returns:
Type | Description |
---|---|
RandAugment transform or ColorJitter |
Source code in training/datasets/datasets_utils.py
637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 |
|
get_mean_and_std_torch(data_dir=None, dataloader=None, num_workers=4, RandomResizeSize=224)
A function for getting the mean and std of large datasets using pytorch dataloader and gpu functionality.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
data_dir |
String, path to none-library dataset folder. For example "/data/Imagenette" or "/data/TinyImagenet" |
None
|
|
dataloader |
a torch DataLoader, as it would feed the data into the trainer (including transforms etc). |
None
|
|
RandomResizeSize |
Int, the size of the RandomResizeCrop as it appears in the DataInterface (for example, for Imagenet, this value should be 224). |
224
|
Returns:
Type | Description |
---|---|
2 lists,mean and std, each one of len 3 (1 for each channel) |
Source code in training/datasets/datasets_utils.py
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 |
|
worker_init_reset_seed(worker_id)
Make sure each process has different random seed, especially for 'fork' method. Check https://github.com/pytorch/pytorch/issues/63311 for more details.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
worker_id |
placeholder (needs to be passed to DataLoader init). |
required |
Source code in training/datasets/datasets_utils.py
657 658 659 660 661 662 663 664 665 666 667 |
|
COCODetectionDataset
Bases: COCOFormatDetectionDataset
Dataset for COCO object detection.
To use this Dataset you need to:
- Download coco dataset:
annotations: http://images.cocodataset.org/annotations/annotations_trainval2017.zip
train2017: http://images.cocodataset.org/zips/train2017.zip
val2017: http://images.cocodataset.org/zips/val2017.zip
- Unzip and organize it as below:
coco
├── annotations
│ ├─ instances_train2017.json
│ ├─ instances_val2017.json
│ └─ ...
└── images
├── train2017
│ ├─ 000000000001.jpg
│ └─ ...
└── val2017
└─ ...
- Install CoCo API: https://github.com/pdollar/coco/tree/master/PythonAPI
- Instantiate the dataset:
>> train_set = COCODetectionDataset(data_dir='.../coco', subdir='images/train2017', json_file='instances_train2017.json', ...)
>> valid_set = COCODetectionDataset(data_dir='.../coco', subdir='images/val2017', json_file='instances_val2017.json', ...)
Source code in training/datasets/detection_datasets/coco_detection.py
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
|
__init__(json_file='instances_train2017.json', subdir='images/train2017', *args, **kwargs)
Parameters:
Name | Type | Description | Default |
---|---|---|---|
json_file |
str
|
Name of the coco json file, that resides in data_dir/annotations/json_file. |
'instances_train2017.json'
|
subdir |
str
|
Sub directory of data_dir containing the data. |
'images/train2017'
|
tight_box_rotation |
bool, whether to use of segmentation maps convex hull as target_seg (check get_sample docs). |
required | |
with_crowd |
Add the crowd groundtruths to getitem kwargs: all_classes_list: all classes list, default is COCO_DETECTION_CLASSES_LIST. |
required |
Source code in training/datasets/detection_datasets/coco_detection.py
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
|
COCOFormatDetectionDataset
Bases: DetectionDataset
Base dataset to load ANY dataset that is with a similar structure to the COCO dataset. - Annotation file (.json). It has to respect the exact same format as COCO, for both the json schema and the bbox format (xywh). - One folder with all the images.
Output format: (x, y, x, y, class_id)
Source code in training/datasets/detection_datasets/coco_format_detection.py
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 |
|
__init__(data_dir, json_annotation_file, images_dir, tight_box_rotation=False, with_crowd=True, class_ids_to_ignore=None, *args, **kwargs)
Parameters:
Name | Type | Description | Default |
---|---|---|---|
data_dir |
str
|
Where the data is stored. |
required |
json_annotation_file |
str
|
Name of the coco json file. Path relative to data_dir. |
required |
images_dir |
str
|
Name of the directory that includes all the images. Path relative to data_dir. |
required |
tight_box_rotation |
bool
|
bool, whether to use of segmentation maps convex hull as target_seg (check get_sample docs). |
False
|
with_crowd |
bool
|
Add the crowd groundtruths to getitem |
True
|
class_ids_to_ignore |
Optional[List[int]]
|
List of class ids to ignore in the dataset. By default, doesnt ignore any class. |
None
|
Source code in training/datasets/detection_datasets/coco_format_detection.py
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 |
|
remove_useless_info(coco, use_seg_info=False)
Remove useless info in coco dataset. COCO object is modified inplace. This function is mainly used for saving memory (save about 30% mem).
Source code in training/datasets/detection_datasets/coco_format_detection.py
187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 |
|
DetectionDataset
Bases: Dataset
Detection dataset.
This is a boilerplate class to facilitate the implementation of datasets.
HOW TO CREATE A DATASET THAT INHERITS FROM DetectionDataSet ? - Inherit from DetectionDataSet - implement the method self.load_annotation to return at least the fields "target" and "img_path" - Call super().__init_ with the required params. //!\ super().init will call self.load_annotation, so make sure that every required attributes are set up before calling super().__init_ (ideally just call it last)
WORKFLOW: - On instantiation: - All annotations are cached. If class_inclusion_list was specified, there is also subclassing at this step. - If cache is True, the images are also cached
- On call (__getitem__) for a specific image index:
- The image and annotations are grouped together in a dict called SAMPLE
- the sample is processed according to th transform
- Only the specified fields are returned by __getitem__
TERMINOLOGY - TARGET: Groundtruth, made of bboxes. The format can vary from one dataset to another - ANNOTATION: Combination of targets (groundtruth) and metadata of the image, but without the image itself. > Has to include the fields "target" and "img_path" > Can include other fields like "crowd_target", "image_info", "segmentation", ... - SAMPLE: Outout of the dataset: > Has to include the fields "target" and "image" > Can include other fields like "crowd_target", "image_info", "segmentation", ... - INDEX: Refers to the index in the dataset. - SAMPLE ID: Refers to the id of sample before droping any annotaion. Let's imagine a situation where the downloaded data is made of 120 images but 20 were drop because they had no annotation. In that case: > We have 120 samples so sample_id will be between 0 and 119 > But only 100 will be indexed so index will be between 0 and 99 > Therefore, we also have len(self) = 100
Source code in training/datasets/detection_datasets/detection_dataset.py
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 |
|
__del__()
Clear the cached images
Source code in training/datasets/detection_datasets/detection_dataset.py
333 334 335 336 |
|
__getitem__(index)
Get the sample post transforms at a specific index of the dataset. The output of this function will be collated to form batches.
Source code in training/datasets/detection_datasets/detection_dataset.py
342 343 344 345 346 347 348 349 |
|
__init__(data_dir, original_target_format, max_num_samples=None, cache=False, cache_dir=None, input_dim=None, transforms=[], all_classes_list=[], class_inclusion_list=None, ignore_empty_annotations=True, target_fields=None, output_fields=None, verbose=True, show_all_warnings=False)
Detection dataset.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
data_dir |
str
|
Where the data is stored |
required |
input_dim |
Optional[Tuple[int, int]]
|
Image size (when loaded, before transforms). |
None
|
original_target_format |
Union[ConcatenatedTensorFormat, DetectionTargetsFormat]
|
Format of targets stored on disk. raw data format, the output format might differ based on transforms. |
required |
max_num_samples |
int
|
If not None, set the maximum size of the dataset by only indexing the first n annotations/images. |
None
|
cache |
bool
|
Whether to cache images or not. |
False
|
cache_dir |
str
|
Path to the directory where cached images will be stored in an optimized format. |
None
|
transforms |
List[DetectionTransform]
|
List of transforms to apply sequentially on sample. |
[]
|
all_classes_list |
Optional[List[str]]
|
All the class names. |
[]
|
class_inclusion_list |
Optional[List[str]]
|
If not None, define the subset of classes to be included as targets. Classes not in this list will excluded from training. Thus, number of classes in model must be adjusted accordingly. |
None
|
ignore_empty_annotations |
bool
|
If True and class_inclusion_list not None, images without any target will be ignored. |
True
|
target_fields |
List[str]
|
List of the fields target fields. This has to include regular target, but can also include crowd target, segmentation target, ... It has to include at least "target" but can include other. |
None
|
output_fields |
List[str]
|
Fields that will be outputed by getitem. It has to include at least "image" and "target" but can include other. |
None
|
verbose |
bool
|
Whether to show additional information or not, such as loading progress. (doesnt include warnings) |
True
|
show_all_warnings |
bool
|
Whether to show all warnings or not. |
False
|
Source code in training/datasets/detection_datasets/detection_dataset.py
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 |
|
__len__()
Get the length of the dataset.
Source code in training/datasets/detection_datasets/detection_dataset.py
338 339 340 |
|
apply_transforms(sample)
Applies self.transforms sequentially to sample
If a transforms has the attribute 'additional_samples_count', additional samples will be loaded and stored in sample["additional_samples"] prior to applying it. Combining with the attribute "non_empty_annotations" will load only additional samples with objects in them.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
sample |
Dict[str, Union[np.ndarray, Any]]
|
Sample to apply the transforms on to (loaded with self.get_sample) |
required |
Returns:
Type | Description |
---|---|
Dict[str, Union[np.ndarray, Any]]
|
Transformed sample |
Source code in training/datasets/detection_datasets/detection_dataset.py
378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 |
|
get_dataset_preprocessing_params()
Return any hardcoded preprocessing + adaptation for PIL.Image image reading (RGB). image_processor as returned as as list of dicts to be resolved by processing factory.
Returns:
Type | Description |
---|---|
Source code in training/datasets/detection_datasets/detection_dataset.py
486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 |
|
get_random_samples(count, non_empty_annotations_only=False)
Load random samples.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
count |
int
|
The number of samples wanted |
required |
non_empty_annotations_only |
bool
|
If true, only return samples with at least 1 annotation |
False
|
Returns:
Type | Description |
---|---|
List[Dict[str, Union[np.ndarray, Any]]]
|
A list of samples satisfying input params |
Source code in training/datasets/detection_datasets/detection_dataset.py
402 403 404 405 406 407 408 409 |
|
get_resized_image(index)
Get the resized image (i.e. either width or height reaches its input_dim) at a specific sample_id, either from cache or by loading from disk, based on self.cached_imgs_padded
Parameters:
Name | Type | Description | Default |
---|---|---|---|
index |
int
|
Image index |
required |
Returns:
Type | Description |
---|---|
np.ndarray
|
Resized image |
Source code in training/datasets/detection_datasets/detection_dataset.py
363 364 365 366 367 368 369 370 371 372 373 374 375 376 |
|
get_sample(index)
Get raw sample, before any transform (beside subclassing).
Parameters:
Name | Type | Description | Default |
---|---|---|---|
index |
int
|
Image index |
required |
Returns:
Type | Description |
---|---|
Dict[str, Union[np.ndarray, Any]]
|
Sample, i.e. a dictionary including at least "image" and "target" |
Source code in training/datasets/detection_datasets/detection_dataset.py
354 355 356 357 358 359 360 361 |
|
plot(max_samples_per_plot=16, n_plots=1, plot_transformed_data=True)
Combine samples of images with bbox into plots and display the result.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
max_samples_per_plot |
int
|
Maximum number of images to be displayed per plot |
16
|
n_plots |
int
|
Number of plots to display (each plot being a combination of img with bbox) |
1
|
plot_transformed_data |
bool
|
If True, the plot will be over samples after applying transforms (i.e. on getitem). If False, the plot will be over the raw samples (i.e. on get_sample) |
True
|
Returns:
Type | Description |
---|---|
Source code in training/datasets/detection_datasets/detection_dataset.py
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 |
|
PascalVOCDetectionDataset
Bases: DetectionDataset
Dataset for Pascal VOC object detection
To use this Dataset you need to: >> train_set = PascalVOCDetectionDataset(download=True, ...)
Dataset structure: ├─images │ ├─ train2012 │ ├─ val2012 │ ├─ VOCdevkit │ │ ├─ VOC2007 │ │ │ ├──JPEGImages │ │ │ ├──SegmentationClass │ │ │ ├──ImageSets │ │ │ ├──ImageSets/Segmentation │ │ │ ├──ImageSets/Main │ │ │ ├──ImageSets/Layout │ │ │ ├──Annotations │ │ │ └──SegmentationObject │ │ └──VOC2012 │ │ ├──JPEGImages │ │ ├──SegmentationClass │ │ ├──ImageSets │ │ ├──ImageSets/Segmentation │ │ ├──ImageSets/Main │ │ ├──ImageSets/Action │ │ ├──ImageSets/Layout │ │ ├──Annotations │ │ └──SegmentationObject │ ├─train2007 │ ├─test2007 │ └─val2007 └─labels ├─train2012 ├─val2012 ├─train2007 ├─test2007 └─val2007
Source code in training/datasets/detection_datasets/pascal_voc_detection.py
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 |
|
__init__(images_sub_directory, download=False, *args, **kwargs)
Dataset for Pascal VOC object detection
Parameters:
Name | Type | Description | Default |
---|---|---|---|
images_sub_directory |
str
|
Sub directory of data_dir that includes images. |
required |
Source code in training/datasets/detection_datasets/pascal_voc_detection.py
67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 |
|
download(data_dir)
staticmethod
Download Pascal dataset in XYXY_LABEL format.
Data extracted form http://host.robots.ox.ac.uk/pascal/VOC/
Source code in training/datasets/detection_datasets/pascal_voc_detection.py
136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 |
|
PascalVOCUnifiedDetectionTrainDataset
Bases: ConcatDataset
Unified Dataset for Pascal VOC object detection
To use this Dataset you need to: >> train_set = PascalVOCUnifiedDetectionTrainDataset(download=True, ...)
Dataset structure: ├─images │ ├─ train2012 │ ├─ val2012 │ ├─ VOCdevkit │ │ ├─ VOC2007 │ │ │ ├──JPEGImages │ │ │ ├──SegmentationClass │ │ │ ├──ImageSets │ │ │ ├──ImageSets/Segmentation │ │ │ ├──ImageSets/Main │ │ │ ├──ImageSets/Layout │ │ │ ├──Annotations │ │ │ └──SegmentationObject │ │ └──VOC2012 │ │ ├──JPEGImages │ │ ├──SegmentationClass │ │ ├──ImageSets │ │ ├──ImageSets/Segmentation │ │ ├──ImageSets/Main │ │ ├──ImageSets/Action │ │ ├──ImageSets/Layout │ │ ├──Annotations │ │ └──SegmentationObject │ ├─train2007 │ ├─test2007 │ └─val2007 └─labels ├─train2012 ├─val2012 ├─train2007 ├─test2007 └─val2007
Source code in training/datasets/detection_datasets/pascal_voc_detection.py
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 |
|
RoboflowDetectionDataset
Bases: COCOFormatDetectionDataset
Dataset that can be used with ANY of the Roboflow100 benchmark datasets for object detection. Checkout the datasets at https://universe.roboflow.com/roboflow-100?ref=blog.roboflow.com
To use this Dataset you need to:
- Follow the official instructions to download Roboflow100: https://github.com/roboflow/roboflow-100-benchmark?ref=roboflow-blog
//!\ To use this dataset, you have to download the "coco" format, NOT the yolov5.
- Your dataset should look like this:
rf100
├── 4-fold-defect
│ ├─ train
│ │ ├─ 000000000001.jpg
│ │ ├─ ...
│ │ └─ _annotations.coco.json
│ ├─ valid
│ │ └─ ...
│ └─ test
│ └─ ...
├── abdomen-mri
│ └─ ...
└── ...
- Install CoCo API: https://github.com/pdollar/coco/tree/master/PythonAPI
- Instantiate the dataset (in this case we load the dataset called "digits-t2eg6")"
>> train_set = RoboflowDetectionDataset(data_dir='<path-to>/rf100', dataset_name="digits-t2eg6", split="train")
>> valid_set = RoboflowDetectionDataset(data_dir='<path-to>/rf100', dataset_name="digits-t2eg6", split="valid")
Note: dataset_name
refers to the official name of the dataset. You can run RoboflowDetectionDataset.list_datasets() to see all available datasets)
OR you can find it in the url of the dataset: https://universe.roboflow.com/roboflow-100/digits-t2eg6 -> digits-t2eg6
Source code in training/datasets/detection_datasets/roboflow/roboflow100.py
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 |
|
metadata: Optional[Dict[str, Union[str, int]]]
property
Category of the dataset. Note that each dataset has one and only one category.
__init__(data_dir, dataset_name, split, *args, **kwargs)
Parameters:
Name | Type | Description | Default |
---|---|---|---|
data_dir |
str
|
Where the data is stored. |
required |
dataset_name |
str
|
One of the 100 dataset name. (You can run RoboflowDetectionDataset.list_datasets() to see all available datasets) |
required |
split |
str
|
train, valid or test. |
required |
Source code in training/datasets/detection_datasets/roboflow/roboflow100.py
45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
|
list_datasets(categories=None)
staticmethod
List all available datasets of specified categories. By default, list all the datasets.
Source code in training/datasets/detection_datasets/roboflow/roboflow100.py
60 61 62 63 |
|
get_dataset_metadata(dataset_name)
Get the metadata of a specific roboflow dataset.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
dataset_name |
str
|
Name of the dataset, as listed in the official repo - https://github.com/roboflow/roboflow-100-benchmark/blob/main/metadata/datasets_stats.csv |
required |
Returns:
Type | Description |
---|---|
Optional[Dict[str, Union[str, int]]]
|
Metadata of the dataset |
Source code in training/datasets/detection_datasets/roboflow/utils.py
15 16 17 18 19 20 21 22 23 24 |
|
get_dataset_num_classes(dataset_name)
Get the number of classes of a specific roboflow dataset.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
dataset_name |
str
|
Name of the dataset, as listed in the official repo - https://github.com/roboflow/roboflow-100-benchmark/blob/main/metadata/datasets_stats.csv |
required |
Returns:
Type | Description |
---|---|
int
|
Number of classes of the dataset. Note that the number of classes in the official documentation is different to the actual one. |
Source code in training/datasets/detection_datasets/roboflow/utils.py
27 28 29 30 31 32 33 34 35 36 |
|
list_datasets(categories=None)
List all available datasets of specified categories. By default, list all the datasets.
Source code in training/datasets/detection_datasets/roboflow/utils.py
9 10 11 12 |
|
YoloDarknetFormatDetectionDataset
Bases: DetectionDataset
Base dataset to load ANY dataset that is with a similar structure to the Yolo/Darknet dataset.
Note: For compatibility reasons, the dataset returns labels in Coco format (XYXY_LABEL) and NOT in Yolo format (LABEL_CXCYWH).
The dataset can have any structure, as long as images_dir
and labels_dir
inside data_dir
.
Each image is expected to have a file with the same name as the label.
Example1:
data_dir
├── images
│ ├─ 0001.jpg
│ ├─ 0002.jpg
│ └─ ...
└── labels
├─ 0001.txt
├─ 0002.txt
└─ ...
>> data_set = YoloDarknetFormatDetectionDataset(data_dir='
Example2: data_dir ├── train │ ├── images │ │ ├─ 0001.jpg │ │ ├─ 0002.jpg │ │ └─ ... │ └── labels │ ├─ 0001.txt │ ├─ 0002.txt │ └─ ... └── val ├── images │ ├─ 434343.jpg │ ├─ 434344.jpg │ └─ ... └── labels ├─ 434343.txt ├─ 434344.txt └─ ...
>> train_set = YoloDarknetFormatDetectionDataset(
data_dir='<path-to>/data_dir', images_dir="train/images", labels_dir="train/labels", classes=[<to-fill>]
)
>> val_set = YoloDarknetFormatDetectionDataset(
data_dir='<path-to>/data_dir', images_dir="val/images", labels_dir="val/labels", classes=[<to-fill>]
)
Example3: data_dir ├── train │ ├─ 0001.jpg │ ├─ 0001.txt │ ├─ 0002.jpg │ ├─ 0002.txt │ └─ ... └── val ├─ 4343.jpg ├─ 4343.txt ├─ 4344.jpg ├─ 4344.txt └─ ...
>> train_set = YoloDarknetFormatDetectionDataset(data_dir='<path-to>/data_dir', images_dir="train", labels_dir="train", classes=[<to-fill>])
>> val_set = YoloDarknetFormatDetectionDataset(data_dir='<path-to>/data_dir', images_dir="val", labels_dir="val", classes=[<to-fill>])
Each label file being in LABEL_NORMALIZED_CXCYWH format: 0 0.33 0.33 0.50 0.44 1 0.21 0.54 0.30 0.60 ...
Output format: XYXY_LABEL (x, y, x, y, class_id)
Source code in training/datasets/detection_datasets/yolo_format_detection.py
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 |
|
__init__(data_dir, images_dir, labels_dir, classes, class_ids_to_ignore=None, ignore_invalid_labels=True, show_all_warnings=False, *args, **kwargs)
Parameters:
Name | Type | Description | Default |
---|---|---|---|
data_dir |
str
|
Where the data is stored. |
required |
images_dir |
str
|
Local path to directory that includes all the images. Path relative to |
required |
labels_dir |
str
|
Local path to directory that includes all the labels. Path relative to |
required |
classes |
List[str]
|
List of class names. |
required |
class_ids_to_ignore |
Optional[List[int]]
|
List of class ids to ignore in the dataset. By default, doesnt ignore any class. |
None
|
ignore_invalid_labels |
bool
|
Whether to ignore labels that fail to be parsed. If True ignores and logs a warning, otherwise raise an error. |
True
|
show_all_warnings |
bool
|
Whether to show every yolo format parser warnings or not. |
False
|
Source code in training/datasets/detection_datasets/yolo_format_detection.py
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 |
|
Mixup and Cutmix
Papers: mixup: Beyond Empirical Risk Minimization (https://arxiv.org/abs/1710.09412)
CutMix: Regularization Strategy to Train Strong Classifiers with Localizable Features (https://arxiv.org/abs/1905.04899)
Code Reference: CutMix: https://github.com/clovaai/CutMix-PyTorch CutMix by timm: https://github.com/rwightman/pytorch-image-models/timm
CollateMixup
Collate with Mixup/Cutmix that applies different params to each element or whole batch A Mixup impl that's performed while collating the batches.
Source code in training/datasets/mixup.py
103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 |
|