Skip to content

Processing

CenterCrop

Bases: ClassificationProcess

Parameters:

Name Type Description Default
size int

Desired output size of the crop.

224
Source code in V3_2/src/super_gradients/training/processing/processing.py
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
@register_processing(Processings.CenterCrop)
class CenterCrop(ClassificationProcess):
    """
    :param size: Desired output size of the crop.
    """

    def __init__(self, size: int = 224):
        super().__init__()
        self.size = size

    def preprocess_image(self, image: np.ndarray) -> Tuple[np.ndarray, None]:
        """Crops the given image at the center.

        :param image: Image, in (H, W, C) format.
        :return:      The center cropped image.
        """
        height, width = image.shape[0], image.shape[1]

        # Calculate the start and end coordinates of the crop.
        start_x = (width - self.size) // 2
        start_y = (height - self.size) // 2
        end_x = start_x + self.size
        end_y = start_y + self.size

        cropped_image = image[start_y:end_y, start_x:end_x]
        return cropped_image, None

preprocess_image(image)

Crops the given image at the center.

Parameters:

Name Type Description Default
image np.ndarray

Image, in (H, W, C) format.

required

Returns:

Type Description
Tuple[np.ndarray, None]

The center cropped image.

Source code in V3_2/src/super_gradients/training/processing/processing.py
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
def preprocess_image(self, image: np.ndarray) -> Tuple[np.ndarray, None]:
    """Crops the given image at the center.

    :param image: Image, in (H, W, C) format.
    :return:      The center cropped image.
    """
    height, width = image.shape[0], image.shape[1]

    # Calculate the start and end coordinates of the crop.
    start_x = (width - self.size) // 2
    start_y = (height - self.size) // 2
    end_x = start_x + self.size
    end_y = start_y + self.size

    cropped_image = image[start_y:end_y, start_x:end_x]
    return cropped_image, None

ComposeProcessing

Bases: Processing

Compose a list of Processing objects into a single Processing object.

Source code in V3_2/src/super_gradients/training/processing/processing.py
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
@register_processing(Processings.ComposeProcessing)
class ComposeProcessing(Processing):
    """Compose a list of Processing objects into a single Processing object."""

    def __init__(self, processings: List[Processing]):
        self.processings = processings

    def preprocess_image(self, image: np.ndarray) -> Tuple[np.ndarray, ComposeProcessingMetadata]:
        """Processing an image, before feeding it to the network."""
        processed_image, metadata_lst = image.copy(), []
        for processing in self.processings:
            processed_image, metadata = processing.preprocess_image(image=processed_image)
            metadata_lst.append(metadata)
        return processed_image, ComposeProcessingMetadata(metadata_lst=metadata_lst)

    def postprocess_predictions(self, predictions: Prediction, metadata: ComposeProcessingMetadata) -> Prediction:
        """Postprocess the model output predictions."""
        postprocessed_predictions = predictions
        for processing, metadata in zip(self.processings[::-1], metadata.metadata_lst[::-1]):
            postprocessed_predictions = processing.postprocess_predictions(postprocessed_predictions, metadata)
        return postprocessed_predictions

postprocess_predictions(predictions, metadata)

Postprocess the model output predictions.

Source code in V3_2/src/super_gradients/training/processing/processing.py
81
82
83
84
85
86
def postprocess_predictions(self, predictions: Prediction, metadata: ComposeProcessingMetadata) -> Prediction:
    """Postprocess the model output predictions."""
    postprocessed_predictions = predictions
    for processing, metadata in zip(self.processings[::-1], metadata.metadata_lst[::-1]):
        postprocessed_predictions = processing.postprocess_predictions(postprocessed_predictions, metadata)
    return postprocessed_predictions

preprocess_image(image)

Processing an image, before feeding it to the network.

Source code in V3_2/src/super_gradients/training/processing/processing.py
73
74
75
76
77
78
79
def preprocess_image(self, image: np.ndarray) -> Tuple[np.ndarray, ComposeProcessingMetadata]:
    """Processing an image, before feeding it to the network."""
    processed_image, metadata_lst = image.copy(), []
    for processing in self.processings:
        processed_image, metadata = processing.preprocess_image(image=processed_image)
        metadata_lst.append(metadata)
    return processed_image, ComposeProcessingMetadata(metadata_lst=metadata_lst)

ImagePermute

Bases: Processing

Permute the image dimensions.

Parameters:

Name Type Description Default
permutation Tuple[int, int, int]

Specify new order of dims. Default value (2, 0, 1) suitable for converting from HWC to CHW format.

(2, 0, 1)
Source code in V3_2/src/super_gradients/training/processing/processing.py
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
@register_processing(Processings.ImagePermute)
class ImagePermute(Processing):
    """Permute the image dimensions.

    :param permutation: Specify new order of dims. Default value (2, 0, 1) suitable for converting from HWC to CHW format.
    """

    def __init__(self, permutation: Tuple[int, int, int] = (2, 0, 1)):
        self.permutation = permutation

    def preprocess_image(self, image: np.ndarray) -> Tuple[np.ndarray, None]:
        processed_image = np.ascontiguousarray(image.transpose(*self.permutation))
        return processed_image, None

    def postprocess_predictions(self, predictions: Prediction, metadata: None) -> Prediction:
        return predictions

NormalizeImage

Bases: Processing

Normalize an image based on means and standard deviation.

Parameters:

Name Type Description Default
mean List[float]

Mean values for each channel.

required
std List[float]

Standard deviation values for each channel.

required
Source code in V3_2/src/super_gradients/training/processing/processing.py
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
@register_processing(Processings.NormalizeImage)
class NormalizeImage(Processing):
    """Normalize an image based on means and standard deviation.

    :param mean:    Mean values for each channel.
    :param std:     Standard deviation values for each channel.
    """

    def __init__(self, mean: List[float], std: List[float]):
        self.mean = np.array(mean).reshape((1, 1, -1)).astype(np.float32)
        self.std = np.array(std).reshape((1, 1, -1)).astype(np.float32)

    def preprocess_image(self, image: np.ndarray) -> Tuple[np.ndarray, None]:
        return (image - self.mean) / self.std, None

    def postprocess_predictions(self, predictions: Prediction, metadata: None) -> Prediction:
        return predictions

Processing

Bases: ABC

Interface for preprocessing and postprocessing methods that are used to prepare images for a model and process the model's output.

Subclasses should implement the preprocess_image and postprocess_predictions methods according to the specific requirements of the model and task.

Source code in V3_2/src/super_gradients/training/processing/processing.py
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
class Processing(ABC):
    """Interface for preprocessing and postprocessing methods that are
    used to prepare images for a model and process the model's output.

    Subclasses should implement the `preprocess_image` and `postprocess_predictions`
    methods according to the specific requirements of the model and task.
    """

    @abstractmethod
    def preprocess_image(self, image: np.ndarray) -> Tuple[np.ndarray, Union[None, ProcessingMetadata]]:
        """Processing an image, before feeding it to the network. Expected to be in (H, W, C) or (H, W)."""
        pass

    @abstractmethod
    def postprocess_predictions(self, predictions: Prediction, metadata: Union[None, ProcessingMetadata]) -> Prediction:
        """Postprocess the model output predictions."""
        pass

postprocess_predictions(predictions, metadata) abstractmethod

Postprocess the model output predictions.

Source code in V3_2/src/super_gradients/training/processing/processing.py
60
61
62
63
@abstractmethod
def postprocess_predictions(self, predictions: Prediction, metadata: Union[None, ProcessingMetadata]) -> Prediction:
    """Postprocess the model output predictions."""
    pass

preprocess_image(image) abstractmethod

Processing an image, before feeding it to the network. Expected to be in (H, W, C) or (H, W).

Source code in V3_2/src/super_gradients/training/processing/processing.py
55
56
57
58
@abstractmethod
def preprocess_image(self, image: np.ndarray) -> Tuple[np.ndarray, Union[None, ProcessingMetadata]]:
    """Processing an image, before feeding it to the network. Expected to be in (H, W, C) or (H, W)."""
    pass

ProcessingMetadata dataclass

Bases: ABC

Metadata including information to postprocess a prediction.

Source code in V3_2/src/super_gradients/training/processing/processing.py
25
26
27
@dataclass
class ProcessingMetadata(ABC):
    """Metadata including information to postprocess a prediction."""

Resize

Bases: ClassificationProcess

Source code in V3_2/src/super_gradients/training/processing/processing.py
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
@register_processing(Processings.Resize)
class Resize(ClassificationProcess):
    def __init__(self, size: int = 224):
        super().__init__()
        self.size = size

    def preprocess_image(self, image: np.ndarray) -> Tuple[np.ndarray, None]:
        """Resize an image.

        :param image: Image, in (H, W, C) format.
        :return:      The resized image.
        """
        image = Image.fromarray(image)
        resized_image = image.resize((self.size, self.size))
        resized_image = np.array(resized_image)

        return resized_image, None

preprocess_image(image)

Resize an image.

Parameters:

Name Type Description Default
image np.ndarray

Image, in (H, W, C) format.

required

Returns:

Type Description
Tuple[np.ndarray, None]

The resized image.

Source code in V3_2/src/super_gradients/training/processing/processing.py
319
320
321
322
323
324
325
326
327
328
329
def preprocess_image(self, image: np.ndarray) -> Tuple[np.ndarray, None]:
    """Resize an image.

    :param image: Image, in (H, W, C) format.
    :return:      The resized image.
    """
    image = Image.fromarray(image)
    resized_image = image.resize((self.size, self.size))
    resized_image = np.array(resized_image)

    return resized_image, None

ReverseImageChannels

Bases: Processing

Reverse the order of the image channels (RGB -> BGR or BGR -> RGB).

Source code in V3_2/src/super_gradients/training/processing/processing.py
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
@register_processing(Processings.ReverseImageChannels)
class ReverseImageChannels(Processing):
    """Reverse the order of the image channels (RGB -> BGR or BGR -> RGB)."""

    def preprocess_image(self, image: np.ndarray) -> Tuple[np.ndarray, None]:
        """Reverse the channel order of an image.

        :param image: Image, in (H, W, C) format.
        :return:      Image with reversed channel order. (RGB if input was BGR, BGR if input was RGB)
        """

        if image.shape[2] != 3:
            raise ValueError("ReverseImageChannels expects 3 channels, got: " + str(image.shape[2]))

        processed_image = image[..., ::-1]
        return processed_image, None

    def postprocess_predictions(self, predictions: Prediction, metadata: None) -> Prediction:
        return predictions

preprocess_image(image)

Reverse the channel order of an image.

Parameters:

Name Type Description Default
image np.ndarray

Image, in (H, W, C) format.

required

Returns:

Type Description
Tuple[np.ndarray, None]

Image with reversed channel order. (RGB if input was BGR, BGR if input was RGB)

Source code in V3_2/src/super_gradients/training/processing/processing.py
111
112
113
114
115
116
117
118
119
120
121
122
def preprocess_image(self, image: np.ndarray) -> Tuple[np.ndarray, None]:
    """Reverse the channel order of an image.

    :param image: Image, in (H, W, C) format.
    :return:      Image with reversed channel order. (RGB if input was BGR, BGR if input was RGB)
    """

    if image.shape[2] != 3:
        raise ValueError("ReverseImageChannels expects 3 channels, got: " + str(image.shape[2]))

    processed_image = image[..., ::-1]
    return processed_image, None

StandardizeImage

Bases: Processing

Standardize image pixel values with img/max_val

Parameters:

Name Type Description Default
max_value float

Current maximum value of the image pixels. (usually 255)

255.0
Source code in V3_2/src/super_gradients/training/processing/processing.py
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
@register_processing(Processings.StandardizeImage)
class StandardizeImage(Processing):
    """Standardize image pixel values with img/max_val

    :param max_value: Current maximum value of the image pixels. (usually 255)
    """

    def __init__(self, max_value: float = 255.0):
        super().__init__()
        self.max_value = max_value

    def preprocess_image(self, image: np.ndarray) -> Tuple[np.ndarray, None]:
        """Reverse the channel order of an image.

        :param image: Image, in (H, W, C) format.
        :return:      Image with reversed channel order. (RGB if input was BGR, BGR if input was RGB)
        """
        processed_image = (image / self.max_value).astype(np.float32)
        return processed_image, None

    def postprocess_predictions(self, predictions: Prediction, metadata: None) -> Prediction:
        return predictions

preprocess_image(image)

Reverse the channel order of an image.

Parameters:

Name Type Description Default
image np.ndarray

Image, in (H, W, C) format.

required

Returns:

Type Description
Tuple[np.ndarray, None]

Image with reversed channel order. (RGB if input was BGR, BGR if input was RGB)

Source code in V3_2/src/super_gradients/training/processing/processing.py
139
140
141
142
143
144
145
146
def preprocess_image(self, image: np.ndarray) -> Tuple[np.ndarray, None]:
    """Reverse the channel order of an image.

    :param image: Image, in (H, W, C) format.
    :return:      Image with reversed channel order. (RGB if input was BGR, BGR if input was RGB)
    """
    processed_image = (image / self.max_value).astype(np.float32)
    return processed_image, None

default_dekr_coco_processing_params()

Processing parameters commonly used for training DEKR on COCO dataset.

Source code in V3_2/src/super_gradients/training/processing/processing.py
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
def default_dekr_coco_processing_params() -> dict:
    """Processing parameters commonly used for training DEKR on COCO dataset."""

    image_processor = ComposeProcessing(
        [
            ReverseImageChannels(),
            KeypointsLongestMaxSizeRescale(output_shape=(640, 640)),
            KeypointsBottomRightPadding(output_shape=(640, 640), pad_value=127),
            StandardizeImage(max_value=255.0),
            NormalizeImage(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
            ImagePermute(permutation=(2, 0, 1)),
        ]
    )

    edge_links = [
        [0, 1],
        [0, 2],
        [1, 2],
        [1, 3],
        [2, 4],
        [3, 5],
        [4, 6],
        [5, 6],
        [5, 7],
        [5, 11],
        [6, 8],
        [6, 12],
        [7, 9],
        [8, 10],
        [11, 12],
        [11, 13],
        [12, 14],
        [13, 15],
        [14, 16],
    ]

    edge_colors = [
        (214, 39, 40),  # Nose -> LeftEye
        (148, 103, 189),  # Nose -> RightEye
        (44, 160, 44),  # LeftEye -> RightEye
        (140, 86, 75),  # LeftEye -> LeftEar
        (227, 119, 194),  # RightEye -> RightEar
        (127, 127, 127),  # LeftEar -> LeftShoulder
        (188, 189, 34),  # RightEar -> RightShoulder
        (127, 127, 127),  # Shoulders
        (188, 189, 34),  # LeftShoulder -> LeftElbow
        (140, 86, 75),  # LeftTorso
        (23, 190, 207),  # RightShoulder -> RightElbow
        (227, 119, 194),  # RightTorso
        (31, 119, 180),  # LeftElbow -> LeftArm
        (255, 127, 14),  # RightElbow -> RightArm
        (148, 103, 189),  # Waist
        (255, 127, 14),  # Left Hip -> Left Knee
        (214, 39, 40),  # Right Hip -> Right Knee
        (31, 119, 180),  # Left Knee -> Left Ankle
        (44, 160, 44),  # Right Knee -> Right Ankle
    ]

    keypoint_colors = [
        (148, 103, 189),
        (31, 119, 180),
        (148, 103, 189),
        (31, 119, 180),
        (148, 103, 189),
        (31, 119, 180),
        (148, 103, 189),
        (31, 119, 180),
        (148, 103, 189),
        (31, 119, 180),
        (148, 103, 189),
        (31, 119, 180),
        (148, 103, 189),
        (31, 119, 180),
        (148, 103, 189),
        (31, 119, 180),
        (148, 103, 189),
    ]
    params = dict(image_processor=image_processor, conf=0.05, edge_links=edge_links, edge_colors=edge_colors, keypoint_colors=keypoint_colors)
    return params

default_ppyoloe_coco_processing_params()

Processing parameters commonly used for training PPYoloE on COCO dataset. TODO: remove once we load it from the checkpoint

Source code in V3_2/src/super_gradients/training/processing/processing.py
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
def default_ppyoloe_coco_processing_params() -> dict:
    """Processing parameters commonly used for training PPYoloE on COCO dataset.
    TODO: remove once we load it from the checkpoint
    """

    image_processor = ComposeProcessing(
        [
            ReverseImageChannels(),
            DetectionRescale(output_shape=(640, 640)),
            NormalizeImage(mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375]),
            ImagePermute(permutation=(2, 0, 1)),
        ]
    )

    params = dict(
        class_names=COCO_DETECTION_CLASSES_LIST,
        image_processor=image_processor,
        iou=0.65,
        conf=0.5,
    )
    return params

default_resnet_imagenet_processing_params()

Processing parameters commonly used for training resnet on Imagenet dataset.

Source code in V3_2/src/super_gradients/training/processing/processing.py
510
511
512
513
514
515
516
517
518
519
def default_resnet_imagenet_processing_params() -> dict:
    """Processing parameters commonly used for training resnet on Imagenet dataset."""
    image_processor = ComposeProcessing(
        [Resize(size=256), CenterCrop(size=224), NormalizeImage(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]), StandardizeImage(), ImagePermute()]
    )
    params = dict(
        class_names=IMAGENET_CLASSES,
        image_processor=image_processor,
    )
    return params

default_yolo_nas_coco_processing_params()

Processing parameters commonly used for training YoloNAS on COCO dataset. TODO: remove once we load it from the checkpoint

Source code in V3_2/src/super_gradients/training/processing/processing.py
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
def default_yolo_nas_coco_processing_params() -> dict:
    """Processing parameters commonly used for training YoloNAS on COCO dataset.
    TODO: remove once we load it from the checkpoint
    """

    image_processor = ComposeProcessing(
        [
            DetectionLongestMaxSizeRescale(output_shape=(636, 636)),
            DetectionCenterPadding(output_shape=(640, 640), pad_value=114),
            StandardizeImage(max_value=255.0),
            ImagePermute(permutation=(2, 0, 1)),
        ]
    )

    params = dict(
        class_names=COCO_DETECTION_CLASSES_LIST,
        image_processor=image_processor,
        iou=0.7,
        conf=0.25,
    )
    return params

default_yolox_coco_processing_params()

Processing parameters commonly used for training YoloX on COCO dataset. TODO: remove once we load it from the checkpoint

Source code in V3_2/src/super_gradients/training/processing/processing.py
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
def default_yolox_coco_processing_params() -> dict:
    """Processing parameters commonly used for training YoloX on COCO dataset.
    TODO: remove once we load it from the checkpoint
    """

    image_processor = ComposeProcessing(
        [
            ReverseImageChannels(),
            DetectionLongestMaxSizeRescale((640, 640)),
            DetectionBottomRightPadding((640, 640), 114),
            ImagePermute((2, 0, 1)),
        ]
    )

    params = dict(
        class_names=COCO_DETECTION_CLASSES_LIST,
        image_processor=image_processor,
        iou=0.65,
        conf=0.1,
    )
    return params

get_pretrained_processing_params(model_name, pretrained_weights)

Get the processing parameters for a pretrained model. TODO: remove once we load it from the checkpoint

Source code in V3_2/src/super_gradients/training/processing/processing.py
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
def get_pretrained_processing_params(model_name: str, pretrained_weights: str) -> dict:
    """Get the processing parameters for a pretrained model.
    TODO: remove once we load it from the checkpoint
    """
    if pretrained_weights == "coco":
        if "yolox" in model_name:
            return default_yolox_coco_processing_params()
        elif "ppyoloe" in model_name:
            return default_ppyoloe_coco_processing_params()
        elif "yolo_nas" in model_name:
            return default_yolo_nas_coco_processing_params()

    if pretrained_weights == "coco_pose" and model_name in ("dekr_w32_no_dc", "dekr_custom"):
        return default_dekr_coco_processing_params()

    if pretrained_weights == "imagenet" and model_name == "resnet18":
        return default_resnet_imagenet_processing_params()

    return dict()