To integrate Albumentations augmentations into your dataset and transforms configuration in the D-FINE repository, you will need to:
Create a Wrapper for Albumentations Augmentations:
Since Albumentations operates on NumPy arrays (not PyTorch tensors or PIL images directly), you'll need to implement a wrapper to bridge between Albumentations and the PyTorch-based transforms framework used in D-FINE.
Modify the Dataset to Support Albumentations:
The dataset's load_item method must ensure that Albumentations-compatible inputs (images and bounding boxes) are passed to the augmentation pipeline.
Update the Config Files:
Extend the configuration to include Albumentations-based augmentations.
Step 1: Create a Wrapper for Albumentations Augmentations
Add a new transform class to handle Albumentations augmentations. This will convert between PIL images and NumPy arrays, apply Albumentations, and handle bounding box transformations.
Add the following to ./repos/D-FINE/src/data/transforms/_transforms.py:
python
import albumentations as A
from albumentations.pytorch import ToTensorV2
import numpy as np
@register()
class AlbumentationsTransform(T.Transform):
"""
Wrapper to apply Albumentations augmentations to images and bounding boxes.
"""
_transformed_types = (
PIL.Image.Image,
Image,
BoundingBoxes,
)
def __init__(self, augmentations: A.Compose):
"""
Args:
augmentations (A.Compose): Albumentations Compose object with augmentations.
"""
super().__init__()
self.augmentations = augmentations
def _transform(self, inpt: Any, params: Dict[str, Any]) -> Any:
"""
Apply Albumentations augmentations.
Args:
inpt: Input data (image, target).
- image: PIL.Image.Image
- target: dict containing bounding boxes and other fields.
Returns:
Transformed image and target.
"""
if isinstance(inpt, tuple):
image, target = inpt
else:
raise ValueError("AlbumentationsTransform expects (image, target) tuple as input.")
# Convert PIL image to NumPy array
image_np = np.array(image)
h, w, _ = image_np.shape
# Prepare bounding boxes in Albumentations format
if "boxes" in target:
boxes = target["boxes"].tolist()
bboxes = [{"bbox": box, "category_id": label} for box, label in zip(boxes, target["labels"].tolist())]
else:
bboxes = []
# Apply Albumentations augmentations
transformed = self.augmentations(image=image_np, bboxes=[b["bbox"] for b in bboxes], category_ids=[b["category_id"] for b in bboxes])
# Update image and bounding boxes
transformed_image = Image.fromarray(transformed["image"])
transformed_bboxes = torch.tensor(transformed["bboxes"], dtype=torch.float32)
target["boxes"] = transformed_bboxes
target["labels"] = torch.tensor(transformed["category_ids"], dtype=torch.int64)
return transformed_image, target
Step 2: Modify Dataset to Support Albumentations
Update the dataset class to ensure compatibility with the Albumentations transforms. Since AlbumentationsTransform will handle bounding boxes and images, you don't need additional changes to the dataset class as long as the D-FINE dataset pipeline sends images and targets.
Make sure the dataset's load_item method (e.g., in CocoDetection) provides the bounding boxes in the correct format for Albumentations, which is already the case in your current implementation. Albumentations expects bounding boxes in [x_min, y_min, x_max, y_max] format, matching the output of the CocoDetection dataset.
Step 3: Update the Configs for Albumentations
You need to define the Albumentations transformations and integrate them into your YAML configuration.
Example Albumentations Pipeline
Create a new file ./repos/D-FINE/src/data/transforms/albumentations_pipeline.py to define your Albumentations augmentations:
This configuration registers the Albumentations pipeline as a transform operation.
Step 4: Validate Changes
Ensure that the Albumentations pipeline is correctly applied by adding debug statements in the AlbumentationsTransform class or testing it on a sample dataset.
Verify that bounding boxes are preserved and properly transformed during augmentations.
Final Notes
Albumentations Bounding Boxes: Ensure the bounding box format [x_min, y_min, x_max, y_max] is consistent across the dataset and Albumentations. This should already be handled in your dataset.
Validation Pipeline: For validation datasets, use a simpler transformation pipeline (e.g., resizing and normalization) as augmentations like cropping are typically unnecessary for validation.
Imports: Ensure all necessary modules (Albumentations, ToTensorV2, etc.) are installed in your environment.
With these changes, your D-FINE repository is now equipped to handle Albumentations augmentations for images and bounding boxes!