### Install and Set Up Pre-commit Hooks Source: https://github.com/albumentations-team/albumentations/blob/main/docs/contributing/environment_setup.md Installs the 'pre-commit' tool and sets up the project's pre-commit hooks to ensure code quality before commits. ```bash pip install pre-commit pre-commit install ``` -------------------------------- ### Install Development Dependencies Source: https://github.com/albumentations-team/albumentations/blob/main/docs/contributing/environment_setup.md Installs all necessary development dependencies for Albumentations from the 'requirements-dev.txt' file. ```bash pip install -r requirements-dev.txt ``` -------------------------------- ### Run Albumentations Test Suite Source: https://github.com/albumentations-team/albumentations/blob/main/docs/contributing/environment_setup.md Executes the project's test suite using pytest to verify that the setup is correct and the code is functioning as expected. ```bash pytest ``` -------------------------------- ### Install Albumentations Source: https://github.com/albumentations-team/albumentations/blob/main/README.md Provides the command to install the latest version of the Albumentations library using pip. It also mentions that other installation options are available in the official documentation. ```bash pip install -U albumentations ``` -------------------------------- ### Install and Use AlbumentationsX Source: https://github.com/albumentations-team/albumentations/blob/main/README.md Instructions for uninstalling the original Albumentations library and installing its successor, AlbumentationsX. It also provides a Python code example demonstrating the usage of AlbumentationsX with the same import statement as the original library. ```bash pip uninstall albumentations pip install albumentationsx ``` ```python import albumentations as A transform = A.Compose([ A.RandomCrop(width=256, height=256), A.HorizontalFlip(p=0.5), A.RandomBrightnessContrast(p=0.2), ]) ``` -------------------------------- ### Run Albumentations Test Suite Source: https://github.com/albumentations-team/albumentations/blob/main/docs/contributing/environment_setup.md Executes the entire test suite for Albumentations using pytest to verify the setup and code integrity. ```bash pytest ``` -------------------------------- ### Install and Run Pre-commit Hooks Source: https://github.com/albumentations-team/albumentations/blob/main/docs/contributing/coding_guidelines.md Instructions for installing and running pre-commit hooks to maintain code quality and formatting within the Albumentations project. This ensures consistency across the codebase. ```bash pip install pre-commit pre-commit install pre-commit run --files $(find albumentations -type f) ``` -------------------------------- ### Install Albumentations in Editable Mode Source: https://github.com/albumentations-team/albumentations/blob/main/docs/contributing/environment_setup.md Installs the Albumentations package in editable mode, allowing for direct code changes to be reflected without reinstallation. ```bash pip install -e . ``` -------------------------------- ### Google-Style Docstring Example Source: https://github.com/albumentations-team/albumentations/blob/main/docs/contributing/coding_guidelines.md Provides an example of a Google-style docstring for a Python function, including type hints, argument descriptions, return value descriptions, and usage examples. ```python def transform(self, image: np.ndarray) -> np.ndarray: """Apply brightness transformation to the image. Args: image: Input image in RGB format. Returns: Transformed image. Examples: >>> transform = Brightness(brightness_range=(-0.2, 0.2)) >>> transformed = transform(image=image) """ ``` -------------------------------- ### DualTransform Example Source: https://github.com/albumentations-team/albumentations/blob/main/docs/contributing/coding_guidelines.md Demonstrates how to write a reproducible example for a DualTransform in Albumentations. It includes sample data preparation, transform initialization with Compose, application of the transform, and retrieval of transformed targets like image, mask, bounding boxes, and keypoints. ```python import numpy as np import albumentations as A # Prepare sample data image = np.random.randint(0, 256, (100, 100, 3), dtype=np.uint8) mask = np.random.randint(0, 2, (100, 100), dtype=np.uint8) bboxes = np.array([[10, 10, 50, 50], [40, 40, 80, 80]], dtype=np.float32) bbox_labels = [1, 2] keypoints = np.array([[20, 30], [60, 70]], dtype=np.float32) keypoint_labels = [0, 1] # Define transform with parameters as tuples when possible transform = A.Compose([ A.HorizontalFlip(p=1.0), ], bbox_params=A.BboxParams(format='pascal_voc', label_fields=['bbox_labels']), keypoint_params=A.KeypointParams(format='xy', label_fields=['keypoint_labels'])) # Apply the transform transformed = transform( image=image, mask=mask, bboxes=bboxes, bbox_labels=bbox_labels, keypoints=keypoints, keypoint_labels=keypoint_labels ) # Get the transformed data transformed_image = transformed['image'] # Horizontally flipped image transformed_mask = transformed['mask'] # Horizontally flipped mask transformed_bboxes = transformed['bboxes'] # Horizontally flipped bounding boxes transformed_keypoints = transformed['keypoints'] # Horizontally flipped keypoints ``` -------------------------------- ### Albumentations Transform Example Source: https://github.com/albumentations-team/albumentations/blob/main/docs/contributing/coding_guidelines.md Demonstrates how to apply a transformation to an image, mask, bounding boxes, and keypoints using the Albumentations library. It shows the process of initializing a transform and accessing the transformed outputs. ```python import albumentations as A # Define a transform with multiple targets transform = A.Compose([ A.HorizontalFlip(p=0.5), A.RandomBrightnessContrast(p=0.2), ]) # Assume you have an image, mask, bboxes, and keypoints # image = ... # mask = ... # bboxes = [...] # Format: [x_min, y_min, x_max, y_max] # keypoints = [...] # Format: [x, y] # Apply the transform transformed = transform(image=image, mask=mask, bboxes=bboxes, keypoints=keypoints) # Get results transformed_image = transformed['image'] transformed_mask = transformed['mask'] transformed_bboxes = transformed['bboxes'] transformed_keypoints = transformed['keypoints'] ``` -------------------------------- ### BadMosaic Initialization Example Source: https://github.com/albumentations-team/albumentations/blob/main/docs/contributing/coding_guidelines.md Demonstrates an incorrect practice in Albumentations transform development where variable data structures are passed via `__init__`, leading to reduced reusability and potential issues with serialization or pipeline composition. ```python # Incorrect - Avoid passing variable data structures via __init__ class BadMosaic(DualTransform): def __init__(self, additional_items: list[dict], target_size: tuple[int, int] = (512, 512), p=0.5): super().__init__(p=p) self.additional_items = additional_items # Discouraged! self.target_size = target_size ``` -------------------------------- ### Base Class Custom Transform Example Source: https://github.com/albumentations-team/albumentations/blob/main/docs/contributing/coding_guidelines.md Illustrates how to create a custom transform inheriting from an Albumentations base class (e.g., BaseDistortion) and use it within a Compose pipeline. The example shows defining custom parameters and distortion logic, then applying it to image and mask data with bounding boxes and keypoints. ```python import numpy as np import albumentations as A class CustomDistortion(A.BaseDistortion): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # Add custom parameters here def get_params_dependent_on_data(self, params, data): height, width = params["shape"][:2] # Generate distortion maps map_x = np.zeros((height, width), dtype=np.float32) map_y = np.zeros((height, width), dtype=np.float32) # Apply your custom distortion logic here # ... return {"map_x": map_x, "map_y": map_y} # Prepare sample data image = np.random.randint(0, 256, (100, 100, 3), dtype=np.uint8) mask = np.random.randint(0, 2, (100, 100), dtype=np.uint8) bboxes = np.array([[10, 10, 50, 50], [40, 40, 80, 80]], dtype=np.float32) bbox_labels = [1, 2] keypoints = np.array([[20, 30], [60, 70]], dtype=np.float32) keypoint_labels = [0, 1] # Apply the custom distortion transform = A.Compose([ CustomDistortion( interpolation=A.cv2.INTER_LINEAR, mask_interpolation=A.cv2.INTER_NEAREST, keypoint_remapping_method="mask", p=1.0 ) ], bbox_params=A.BboxParams(format='pascal_voc', label_fields=['bbox_labels']), keypoint_params=A.KeypointParams(format='xy', label_fields=['keypoint_labels'])) # Apply the transform transformed = transform( image=image, mask=mask, bboxes=bboxes, bbox_labels=bbox_labels, ``` -------------------------------- ### Albumentations for Specific Tasks Source: https://github.com/albumentations-team/albumentations/blob/main/README.md Guidance on using Albumentations for specific computer vision tasks like classification, segmentation, or object detection. Links to detailed articles and examples are provided. ```python import albumentations as A # Example for classification transform_classification = A.Compose([ A.RandomResizedCrop(224, 224), A.HorizontalFlip(), A.Normalize(), ]) # Example for segmentation transform_segmentation = A.Compose([ A.RandomCrop(width=128, height=128), A.HorizontalFlip(), A.ShiftScaleRotate(shift_limit=0.0625, scale_limit=0.1, rotate_limit=45, p=0.5), A.Normalize(), ], bbox_params=A.BboxParams(format='pascal_voc', label_fields=['category'])) # Example for object detection transform_detection = A.Compose([ A.RandomSizedBBoxSafeSafeCrop(width=512, height=512, erosion_rate=0.2), A.HorizontalFlip(), A.RandomBrightnessContrast(p=0.2), ], bbox_params=A.BboxParams(format='pascal_voc', min_area=32.0, min_visibility=0.1, label_fields=['category'])) ``` -------------------------------- ### Incorrect Transform without InitSchema Source: https://github.com/albumentations-team/albumentations/blob/main/docs/contributing/coding_guidelines.md Shows an example of an Albumentations transform that is missing the required `InitSchema` class, which is necessary for proper parameter validation and handling. ```python # Incorrect - missing InitSchema class RandomGravel(ImageOnlyTransform): def __init__(self, slant_range: tuple[float, float], brightness_coefficient: float, p: float = 0.5): super().__init__(p=p) self.slant_range = slant_range self.brightness_coefficient = brightness_coefficient ``` -------------------------------- ### Avoiding Union Types for Parameters Source: https://github.com/albumentations-team/albumentations/blob/main/docs/contributing/coding_guidelines.md Explains the guideline to avoid using `Union` types for parameters where a range is more appropriate. It shows how to use a range with identical start and end values for fixed settings. ```python # Correct scale_range: tuple[float, float] = (0.5, 1.5) # Avoid scale: float | tuple[float, float] = 1.0 # For fixed values, use same value for both range ends: brightness_range = (0.1, 0.1) # Fixed brightness of 0.1 ``` -------------------------------- ### Using get_params_dependent_on_data Source: https://github.com/albumentations-team/albumentations/blob/main/docs/contributing/coding_guidelines.md Provides an example of the `get_params_dependent_on_data` method, showing how to access image shape and target data (image, mask, bboxes, keypoints) to calculate transform parameters dynamically based on the input. ```python def get_params_dependent_on_data( self, params: dict[str, Any], data: dict[str, Any] ) -> dict[str, Any]: # Access image shape - always available height, width = params["shape"][:2] # Access targets if they were passed to transform image = data.get("image") # Original image mask = data.get("mask") # Segmentation mask bboxes = data.get("bboxes") # Bounding boxes keypoints = data.get("keypoints") # Keypoint coordinates # Example: Calculate parameters based on image size crop_size = min(height, width) // 2 center_x = width // 2 center_y = height // 2 return { "crop_size": crop_size, "center": (center_x, center_y) } ``` -------------------------------- ### Listing Python Dependencies Source: https://github.com/albumentations-team/albumentations/blob/main/requirements-dev.txt This snippet lists the Python packages required to run or develop the project, along with minimum version constraints. These dependencies are typically installed using package managers like pip. ```Python requirements deepdiff>=8.0.1 eval-type-backport pre_commit>=3.5.0 pytest>=8.3.3 pytest_cov>=5.0.0 pytest_mock>=3.14.0 pytz requests>=2.31.0 scikit-image scikit-learn tomli>=2.0.1 torch>=2.3.1 torchvision>=0.18.1 types-PyYAML types-setuptools ``` -------------------------------- ### Clone Albumentations Repository Source: https://github.com/albumentations-team/albumentations/blob/main/docs/contributing/environment_setup.md Clones the Albumentations repository from GitHub to your local machine and navigates into the project directory. ```bash git clone https://github.com/YOUR_USERNAME/albumentations.git cd albumentations ``` -------------------------------- ### Manually Run Pre-commit Hooks Source: https://github.com/albumentations-team/albumentations/blob/main/docs/contributing/environment_setup.md Manually runs all configured pre-commit hooks on all files within the Albumentations project directory. ```bash pre-commit run --files $(find albumentations -type f) ``` -------------------------------- ### Create and Activate Virtual Environment (Linux/macOS) Source: https://github.com/albumentations-team/albumentations/blob/main/docs/contributing/environment_setup.md Creates a Python virtual environment named 'env' and activates it for Linux and macOS systems. ```bash python3 -m venv env source env/bin/activate ``` -------------------------------- ### Create and Activate Virtual Environment (Windows PowerShell) Source: https://github.com/albumentations-team/albumentations/blob/main/docs/contributing/environment_setup.md Creates a Python virtual environment named 'env' and activates it using PowerShell on Windows. ```bash python -m venv env env\Scripts\activate.ps1 ``` -------------------------------- ### Create and Activate Virtual Environment (Windows cmd.exe) Source: https://github.com/albumentations-team/albumentations/blob/main/docs/contributing/environment_setup.md Creates a Python virtual environment named 'env' and activates it using the cmd.exe shell on Windows. ```bash python -m venv env env\Scripts\activate.bat ``` -------------------------------- ### System Information Source: https://github.com/albumentations-team/albumentations/blob/main/README.md Provides details about the system used for benchmarking, including platform, processor, CPU count, and Python version. ```text Platform: macOS-15.1-arm64-arm-64bit Processor: arm CPU Count: 16 Python Version: 3.12.8 ``` -------------------------------- ### Albumentations 3D Transforms Overview Source: https://github.com/albumentations-team/albumentations/blob/main/README.md Lists 3D transforms supported by Albumentations, indicating their compatibility with Volume, Mask3D, and Keypoints. Each transform links to its detailed documentation. ```markdown | Transform | Volume | Mask3D | Keypoints | | :------------------------------------------------------------------------------ | :----: | :----: | :-------: | | [CenterCrop3D](https://explore.albumentations.ai/transform/CenterCrop3D) | ✓ | ✓ | ✓ | | [CoarseDropout3D](https://explore.albumentations.ai/transform/CoarseDropout3D) | ✓ | ✓ | ✓ | | [CubicSymmetry](https://explore.albumentations.ai/transform/CubicSymmetry) | ✓ | ✓ | ✓ | | [Pad3D](https://explore.albumentations.ai/transform/Pad3D) | ✓ | ✓ | ✓ | | [PadIfNeeded3D](https://explore.albumentations.ai/transform/PadIfNeeded3D) | ✓ | ✓ | ✓ | | [RandomCrop3D](https://explore.albumentations.ai/transform/RandomCrop3D) | ✓ | ✓ | ✓ | ``` -------------------------------- ### Simple Albumentations Augmentation Pipeline Source: https://github.com/albumentations-team/albumentations/blob/main/README.md Demonstrates how to create a basic augmentation pipeline using Albumentations, including random cropping, horizontal flipping, and brightness/contrast adjustments. It shows how to read an image, apply the transformations, and retrieve the augmented image. ```python import albumentations as A import cv2 # Declare an augmentation pipeline transform = A.Compose([ A.RandomCrop(width=256, height=256), A.HorizontalFlip(p=0.5), A.RandomBrightnessContrast(p=0.2), ]) # Read an image with OpenCV and convert it to the RGB colorspace image = cv2.imread("image.jpg") image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) # Augment an image transformed = transform(image=image) transformed_image = transformed["image"] ``` -------------------------------- ### Explore Albumentations Online Demo Source: https://github.com/albumentations-team/albumentations/blob/main/README.md Access the online demo to experiment with Albumentations augmentations on various images and visualize the results. This interactive tool helps in understanding the effects of different transformations. ```html Online Demo of Albumentations ``` -------------------------------- ### Albumentations Transformations Overview Source: https://github.com/albumentations-team/albumentations/blob/main/README.md This section provides an overview of the transformations available in the Albumentations library. Each transformation is linked to its detailed documentation page. ```APIDOC Pad: Description: Pads the input image to a specified size. Parameters: - always_apply (bool): Whether to always apply the transform. - p (float): Probability of applying the transform. PadIfNeeded: Description: Pads the input image if its dimensions are smaller than the specified size. Parameters: - min_height (int): Minimum height of the image. - min_width (int): Minimum width of the image. - always_apply (bool): Whether to always apply the transform. - p (float): Probability of applying the transform. Perspective: Description: Applies a perspective transformation to the image. Parameters: - scale (tuple): Range of scaling factors. - keep_size (bool): Whether to keep the original image size. - always_apply (bool): Whether to always apply the transform. - p (float): Probability of applying the transform. PiecewiseAffine: Description: Applies a piecewise affine transformation to the image. Parameters: - scale (tuple): Range of scaling factors for the grid. - nb_rows (int): Number of rows in the grid. - nb_cols (int): Number of columns in the grid. - always_apply (bool): Whether to always apply the transform. - p (float): Probability of applying the transform. PixelDropout: Description: Randomly drops pixels in the image. Parameters: - dropout_prob (float): Probability of dropping a pixel. - always_apply (bool): Whether to always apply the transform. - p (float): Probability of applying the transform. RandomCrop: Description: Randomly crops a portion of the image. Parameters: - height (int): Height of the crop. - width (int): Width of the crop. - always_apply (bool): Whether to always apply the transform. - p (float): Probability of applying the transform. RandomCropFromBorders: Description: Randomly crops the image from its borders. Parameters: - height (int): Height of the crop. - width (int): Width of the crop. - always_apply (bool): Whether to always apply the transform. - p (float): Probability of applying the transform. RandomCropNearBBox: Description: Randomly crops the image near bounding boxes. Parameters: - bounding_box_params (dict): Parameters for bounding box handling. - always_apply (bool): Whether to always apply the transform. - p (float): Probability of applying the transform. RandomGridShuffle: Description: Randomly shuffles the grid of the image. Parameters: - grid_height (int): Height of the grid. - grid_width (int): Width of the grid. - always_apply (bool): Whether to always apply the transform. - p (float): Probability of applying the transform. RandomResizedCrop: Description: Randomly crops and resizes the image. Parameters: - height (int): Height of the resized crop. - width (int): Width of the resized crop. - scale (tuple): Range of scaling factors. - ratio (tuple): Range of aspect ratio factors. - always_apply (bool): Whether to always apply the transform. - p (float): Probability of applying the transform. RandomRotate90: Description: Randomly rotates the image by 90 degrees. Parameters: - limit (int): Maximum number of 90-degree rotations. - always_apply (bool): Whether to always apply the transform. - p (float): Probability of applying the transform. RandomScale: Description: Randomly scales the image. Parameters: - scale_limit (tuple): Range of scaling factors. - always_apply (bool): Whether to always apply the transform. - p (float): Probability of applying the transform. RandomSizedBBoxSafeCrop: Description: Randomly crops the image while ensuring bounding boxes are safe. Parameters: - height (int): Height of the crop. - width (int): Width of the crop. - erosion_rate (float): Erosion rate for bounding box safety. - always_apply (bool): Whether to always apply the transform. - p (float): Probability of applying the transform. RandomSizedCrop: Description: Randomly crops the image to a random size and aspect ratio. Parameters: - height (int): Height of the crop. - width (int): Width of the crop. - scale (tuple): Range of scaling factors. - ratio (tuple): Range of aspect ratio factors. - always_apply (bool): Whether to always apply the transform. - p (float): Probability of applying the transform. Resize: Description: Resizes the image to a specified size. Parameters: - height (int): Target height. - width (int): Target width. - always_apply (bool): Whether to always apply the transform. - p (float): Probability of applying the transform. Rotate: Description: Rotates the image by a random angle. Parameters: - limit (int): Maximum angle of rotation. - always_apply (bool): Whether to always apply the transform. - p (float): Probability of applying the transform. SafeRotate: Description: Rotates the image by a random angle, ensuring no data loss. Parameters: - limit (int): Maximum angle of rotation. - always_apply (bool): Whether to always apply the transform. - p (float): Probability of applying the transform. ShiftScaleRotate: Description: Applies shift, scale, and rotate transformations. Parameters: - shift_limit (float): Range of shift. - scale_limit (float): Range of scale. - rotate_limit (int): Range of rotation. - always_apply (bool): Whether to always apply the transform. - p (float): Probability of applying the transform. SmallestMaxSize: Description: Resizes the image such that the smallest side is a specified size. Parameters: - max_size (int): The size of the smallest side. - always_apply (bool): Whether to always apply the transform. - p (float): Probability of applying the transform. SquareSymmetry: Description: Applies a square symmetry transformation. Parameters: - always_apply (bool): Whether to always apply the transform. - p (float): Probability of applying the transform. ThinPlateSpline: Description: Applies a Thin Plate Spline transformation. Parameters: - scale (tuple): Range of scaling factors. - always_apply (bool): Whether to always apply the transform. - p (float): Probability of applying the transform. TimeMasking: Description: Masks a contiguous segment of frames in a video. Parameters: - num_masks (int): Number of masks to apply. - max_width (int): Maximum width of the mask. - always_apply (bool): Whether to always apply the transform. - p (float): Probability of applying the transform. TimeReverse: Description: Reverses the order of frames in a video. Parameters: - always_apply (bool): Whether to always apply the transform. - p (float): Probability of applying the transform. Transpose: Description: Transposes the image. Parameters: - always_apply (bool): Whether to always apply the transform. - p (float): Probability of applying the transform. VerticalFlip: Description: Flips the image vertically. Parameters: - always_apply (bool): Whether to always apply the transform. - p (float): Probability of applying the transform. XYMasking: Description: Masks a contiguous segment of pixels in the image. Parameters: - num_masks (int): Number of masks to apply. - max_width (int): Maximum width of the mask. - always_apply (bool): Whether to always apply the transform. - p (float): Probability of applying the transform. ``` -------------------------------- ### Contributing to Albumentations Source: https://github.com/albumentations-team/albumentations/blob/main/README.md Information on how to contribute to the Albumentations project. This includes a link to the CONTRIBUTING.md file for detailed guidelines on creating pull requests. ```APIDOC Project Contribution: To contribute to the Albumentations repository, please refer to the detailed documentation provided in the [CONTRIBUTING.md](CONTRIBUTING.md) file. This guide outlines the process for submitting pull requests and adhering to project standards. ``` -------------------------------- ### Library Versions Source: https://github.com/albumentations-team/albumentations/blob/main/README.md Lists the versions of various libraries used in the benchmark, including Albumentations and related augmentation libraries. ```text albumentations: 2.0.4 augly: 1.0.0 imgaug: 0.4.0 kornia: 0.8.0 torchvision: 0.20.1 ``` -------------------------------- ### List of All Available Augmentations Source: https://github.com/albumentations-team/albumentations/blob/main/README.md Reference to a comprehensive list of all augmentations provided by the Albumentations library. This section details each augmentation and its applicability. ```markdown [List of all available augmentations](#list-of-augmentations) ``` -------------------------------- ### Benchmark Parameters Source: https://github.com/albumentations-team/albumentations/blob/main/README.md Outlines the parameters used during the benchmark tests, such as the number of images processed and the number of runs per transform. ```text Number of images: 2000 Runs per transform: 5 Max warmup iterations: 1000 ``` -------------------------------- ### Open Source Projects Using Albumentations Source: https://github.com/albumentations-team/albumentations/blob/main/README.md A list of open-source projects that depend on or utilize the Albumentations library, showcasing its adoption in the broader development community. ```markdown [Open source projects that use Albumentations](https://github.com/albumentations-team/albumentations/network/dependents?dependent_type=PACKAGE) ``` -------------------------------- ### Performance Comparison Table Source: https://github.com/albumentations-team/albumentations/blob/main/README.md This table summarizes the performance of different image augmentation libraries. It lists the number of uint8 images processed per second on a single CPU thread and the speedup factor of Albumentations compared to the fastest alternative for each transform. '-' indicates that the library does not support the specific transform. ```markdown | Transform | albumentations
2.0.4 | augly
1.0.0 | imgaug
0.4.0 | kornia
0.8.0 | torchvision
0.20.1 | Speedup
(Alb/fastest other) | |:---------------------|:--------------------------|:-----------------|:------------------|:------------------|:------------------------|:---------------------------------| | Affine | **1445 ± 9** | - | 1328 ± 16 | 248 ± 6 | 188 ± 2 | 1.09x | | AutoContrast | **1657 ± 13** | - | - | 541 ± 8 | 344 ± 1 | 3.06x | | Blur | **7657 ± 114** | 386 ± 4 | 5381 ± 125 | 265 ± 11 | - | 1.42x | | Brightness | **11985 ± 455** | 2108 ± 32 | 1076 ± 32 | 1127 ± 27 | 854 ± 13 | 5.68x | | CLAHE | **647 ± 4** | - | 555 ± 14 | 165 ± 3 | - | 1.17x | | CenterCrop128 | **119293 ± 2164** | - | - | - | - | N/A | | ChannelDropout | **11534 ± 306** | - | - | 2283 ± 24 | - | 5.05x | | ChannelShuffle | **6772 ± 109** | - | 1252 ± 26 | 1328 ± 44 | 4417 ± 234 | 1.53x | | CoarseDropout | **18962 ± 1346** | - | 1190 ± 22 | - | - | 15.93x | | ColorJitter | **1020 ± 91** | 418 ± 5 | - | 104 ± 4 | 87 ± 1 | 2.44x | | Contrast | **12394 ± 363** | 1379 ± 25 | 717 ± 5 | 1109 ± 41 | 602 ± 13 | 8.99x | | CornerIllumination | **484 ± 7** | - | - | 452 ± 3 | - | 1.07x | | Elastic | 374 ± 2 | - | **395 ± 14** | 1 ± 0 | 3 ± 0 | 0.95x | | Equalize | **1236 ± 21** | - | 814 ± 11 | 306 ± 1 | 795 ± 3 | 1.52x | | Erasing | **27451 ± 2794** | - | - | 1210 ± 27 | 3577 ± 49 | 7.67x | | GaussianBlur | **2350 ± 118** | 387 ± 4 | 1460 ± 23 | 254 ± 5 | 127 ± 4 | 1.61x | | GaussianIllumination | **720 ± 7** | - | - | 436 ± 13 | - | 1.65x | | GaussianNoise | **315 ± 4** | - | 263 ± 9 | 125 ± 1 | - | 1.20x | | Grayscale | **32284 ± 1130** | 6088 ± 107 | 3100 ± 24 | 1201 ± 52 | 2600 ± 23 | 5.30x | | HSV | **1197 ± 23** | - | - | - | - | N/A | | HorizontalFlip | **14460 ± 368** | 8808 ± 1012 | 9599 ± 495 | 1297 ± 13 | 2486 ± 107 | 1.51x | | Hue | **1944 ± 64** | - | - | 150 ± 1 | - | 12.98x | | Invert | **27665 ± 3803** | - | 3682 ± 79 | 2881 ± 43 | 4244 ± 30 | 6.52x | | JpegCompression | **1321 ± 33** | 1202 ± 19 | 687 ± 26 | 120 ± 1 | 889 ± 7 | 1.10x | | LinearIllumination | 479 ± 5 | - | - | **708 ± 6** | - | 0.68x | ``` -------------------------------- ### Update Albumentations Transforms Documentation Source: https://github.com/albumentations-team/albumentations/blob/main/docs/contributing/coding_guidelines.md Command to generate updated documentation for Albumentations transforms, listing their supported targets. This is crucial for maintaining accurate README files when transforms are added or modified. ```bash python -m tools.make_transforms_docs make ``` -------------------------------- ### Channel Flexibility in Transforms Source: https://github.com/albumentations-team/albumentations/blob/main/docs/contributing/coding_guidelines.md Illustrates how to write transforms that can handle an arbitrary number of image channels or explicitly require a specific number of channels (e.g., RGB). This ensures transforms are robust to different image formats. ```python import numpy as np # Assume rgb_to_hsv is defined elsewhere # Correct - works with any number of channels def apply_any_channels(self, img: np.ndarray, **params) -> np.ndarray: # img shape is (H, W, C), works for any C return img * self.factor # Also correct - explicitly requires RGB def apply_rgb_channels(self, img: np.ndarray, **params) -> np.ndarray: if img.shape[-1] != 3: raise ValueError("Transform requires RGB image") return rgb_to_hsv(img) # RGB-specific processing ``` -------------------------------- ### Albumentations Community Links Source: https://github.com/albumentations-team/albumentations/blob/main/README.md Links to the official community channels for Albumentations, including LinkedIn, Twitter, and Discord, for users to connect and engage with the project. ```APIDOC Community Engagement: - LinkedIn: https://www.linkedin.com/company/albumentations/ - Twitter: https://twitter.com/albumentations - Discord: https://discord.gg/AKPrrDYNAt ``` -------------------------------- ### Python Type Hinting Standards Source: https://github.com/albumentations-team/albumentations/blob/main/docs/contributing/coding_guidelines.md Demonstrates the correct usage of Python type hints according to modern standards (Python 3.10+). It shows the preferred syntax for type annotations, including the use of `|` for unions and optional types. ```python # Correct def transform(self, value: float, range: tuple[float, float]) -> float: # Incorrect - don't use capital-case types def transform(self, value: float, range: Tuple[float, float]) -> Float: # Correct def process(value: int | float | None) -> str: # Incorrect def process(value: Optional[Union[int, float]) -> str: ``` -------------------------------- ### Parameter Sampling in get_params Source: https://github.com/albumentations-team/albumentations/blob/main/docs/contributing/coding_guidelines.md Shows how to correctly perform random operations for parameter sampling within the `get_params` method, ensuring that random choices are made during parameter generation and not in `apply_xxx` or `__init__`. ```python def get_params(self): return { "brightness": self.random_generator.uniform( self.brightness_range[0], self.brightness_range[1] ) } ``` -------------------------------- ### Correct apply_xxx Method Signature Source: https://github.com/albumentations-team/albumentations/blob/main/docs/contributing/coding_guidelines.md Demonstrates the correct way to define `apply_xxx` methods in Albumentations transforms, specifically highlighting the avoidance of default arguments in these methods. ```python # Correct def apply_to_mask(self, mask: np.ndarray, fill_mask: int) -> np.ndarray: # Incorrect def apply_to_mask(self, mask: np.ndarray, fill_mask: int = 0) -> np.ndarray: ``` -------------------------------- ### Image Center Calculation Functions Source: https://github.com/albumentations-team/albumentations/blob/main/docs/contributing/coding_guidelines.md Demonstrates the correct usage of helper functions for calculating center points in image transformations. `center()` is used for images, masks, and keypoints, while `center_bbox()` is specifically for bounding boxes. ```python # Correct - using helper function for image/mask/keypoint center from albumentations.augmentations.geometric.functional import center center_x, center_y = center(image_shape) # Returns ((width-1)/2, (height-1)/2) # Incorrect - manual calculation might miss the -1 center_x = width / 2 # Wrong! center_y = height / 2 # Wrong! ``` ```python # Correct - using helper function for bounding box center from albumentations.augmentations.geometric.functional import center_bbox center_x, center_y = center_bbox(image_shape) # Returns (width/2, height/2) # Incorrect - using wrong center calculation center_x, center_y = center(image_shape) # Wrong for bboxes! ``` -------------------------------- ### Albumentations Transformation Performance Benchmarks Source: https://github.com/albumentations-team/albumentations/blob/main/README.md This table summarizes the performance benchmarks for various image augmentation transformations in the Albumentations library. It includes metrics like mean execution time and standard deviation for different operations. ```APIDOC Transformation Performance Benchmarks: | Transformation | CPU (ms) ± std | GPU (ms) ± std | CPU Batch (ms) ± std | GPU Batch (ms) ± std | CPU Batch (ms) ± std | Speedup | |-----------------------|----------------|----------------|----------------------|----------------------|----------------------|---------| | MedianBlur | 1229 ± 9 | - | 1152 ± 14 | 6 ± 0 | - | 1.07x | | MotionBlur | 3521 ± 25 | - | 928 ± 37 | 159 ± 1 | - | 3.79x | | Normalize | 1819 ± 49 | - | - | 1251 ± 14 | 1018 ± 7 | 1.45x | | OpticalDistortion | 661 ± 7 | - | - | 174 ± 0 | - | 3.80x | | Pad | 48589 ± 2059 | - | - | - | 4889 ± 183 | 9.94x | | Perspective | 1206 ± 3 | - | 908 ± 8 | 154 ± 3 | 147 ± 5 | 1.33x | | PlankianJitter | 3221 ± 63 | - | - | 2150 ± 52 | - | 1.50x | | PlasmaBrightness | 168 ± 2 | - | - | 85 ± 1 | - | 1.98x | | PlasmaContrast | 145 ± 3 | - | - | 84 ± 0 | - | 1.71x | | PlasmaShadow | 183 ± 5 | - | - | 216 ± 5 | - | 0.85x | | Posterize | 12979 ± 1121 | - | 3111 ± 95 | 836 ± 30 | 4247 ± 26 | 3.06x | | RGBShift | 3391 ± 104 | - | - | 896 ± 9 | - | 3.79x | | Rain | 2043 ± 115 | - | - | 1493 ± 9 | - | 1.37x | | RandomCrop128 | 111859 ± 1374 | 45395 ± 934 | 21408 ± 622 | 2946 ± 42 | 31450 ± 249 | 2.46x | | RandomGamma | 12444 ± 753 | - | 3504 ± 72 | 230 ± 3 | - | 3.55x | | RandomResizedCrop | 4347 ± 37 | - | - | 661 ± 16 | 837 ± 37 | 5.19x | | Resize | 3532 ± 67 | 1083 ± 21 | 2995 ± 70 | 645 ± 13 | 260 ± 9 | 1.18x | | Rotate | 2912 ± 68 | 1739 ± 105 | 2574 ± 10 | 256 ± 2 | 258 ± 4 | 1.13x | | SaltAndPepper | 629 ± 6 | - | - | 480 ± 12 | - | 1.31x | | Saturation | 1596 ± 24 | - | 495 ± 3 | 155 ± 2 | - | 3.22x | | Sharpen | 2346 ± 10 | - | 1101 ± 30 | 201 ± 2 | 220 ± 3 | 2.13x | | Shear | 1299 ± 11 | - | 1244 ± 14 | 261 ± 1 | - | 1.04x | | Snow | 611 ± 9 | - | - | 143 ± 1 | - | 4.28x | | Solarize | 11756 ± 481 | - | 3843 ± 80 | 263 ± 6 | 1032 ± 14 | 3.06x | | ThinPlateSpline | 82 ± 1 | - | - | 58 ± 0 | - | 1.41x | | VerticalFlip | 32386 ± 936 | 16830 ± 1653 | 19935 ± 1708 | 2872 ± 37 | 4696 ± 161 | 1.62x | ``` -------------------------------- ### Correct InitSchema for Parameter Validation Source: https://github.com/albumentations-team/albumentations/blob/main/docs/contributing/coding_guidelines.md Illustrates the correct implementation of an `InitSchema` class within an Albumentations transform for validating and potentially converting input parameters before the `__init__` method is called. It shows proper use of `Annotated` and `Field` for validation rules. ```python # Correct - full parameter validation class RandomGravel(ImageOnlyTransform): class InitSchema(BaseTransformInitSchema): slant_range: Annotated[tuple[float, float], AfterValidator(nondecreasing)] brightness_coefficient: float = Field(gt=0, le=1) def __init__(self, slant_range: tuple[float, float], brightness_coefficient: float, p: float = 0.5): super().__init__(p=p) self.slant_range = slant_range self.brightness_coefficient = brightness_coefficient ``` -------------------------------- ### CropAndPad Transform Documentation Source: https://github.com/albumentations-team/albumentations/blob/main/README.md The CropAndPad transform crops an image to a specified size and pads it if necessary. It supports images, masks, bounding boxes, keypoints, volumes, and 3D masks. ```APIDOC CropAndPad: __init__(size=(512, 512), pad_mode='constant', pad_cval=0, keep_size=True, always_apply=False, p=0.5) Crops an image to a specified size and pads it if necessary. Parameters: size (tuple, optional): The target size (height, width). Defaults to (512, 512). pad_mode (str, optional): Padding mode. Defaults to 'constant'. pad_cval (int, optional): Value to fill padded regions with. Defaults to 0. keep_size (bool, optional): Whether to keep the original size if the cropped image is larger. Defaults to True. always_apply (bool, optional): Whether to always apply the transform. Defaults to False. p (float, optional): Probability of applying the transform. Defaults to 0.5. Supported Targets: Image, Mask, BBoxes, Keypoints, Volume, Mask3D ``` -------------------------------- ### Transform Naming Convention Source: https://github.com/albumentations-team/albumentations/blob/main/docs/contributing/coding_guidelines.md Illustrates the preferred naming convention for new transforms in Albumentations, specifically advising against the use of the 'Random' prefix. ```python # Correct class Brightness(ImageOnlyTransform): # Incorrect (historical pattern) class RandomBrightness(ImageOnlyTransform): ```