Skip to content

Image Pipeline Playground

feat(backend/nodes): albumentations catalog, dual ports, annotations

Mohammad Rajaei9249dd434115
diff --git a/backend/app/nodes/__init__.py b/backend/app/nodes/__init__.py
index 7aae365..7e059bf 100644
--- a/backend/app/nodes/__init__.py
+++ b/backend/app/nodes/__init__.py
@@ -1,6 +1,7 @@
"""Register all built-in OpenCV nodes."""
from app.engine.registry import registry
+from app.nodes.albumentations_aug import build_albumentations_nodes
from app.nodes.analysis import (
AdaptiveThresholdNode,
BlurDetectNode,
@@ -10,6 +11,7 @@ from app.nodes.analysis import (
HistogramEqualizeNode,
NormalizeNode,
)
+from app.nodes.annotations import AnnotationsNode
from app.nodes.clustering import DominantColorsHistNode, KMeansColorsNode
from app.nodes.color import (
BrightnessContrastNode,
@@ -68,6 +70,7 @@ def register_builtin_nodes() -> None:
for node in (
LoadImageNode(),
BlankImageNode(),
+ AnnotationsNode(),
SaveImageNode(),
PreviewNode(),
ToGrayNode(),
@@ -122,6 +125,7 @@ def register_builtin_nodes() -> None:
FlipNode(),
RandomBrightnessContrastNode(),
GaussianNoiseNode(),
+ *build_albumentations_nodes(),
):
if not registry.has(node.type):
registry.register(node)
diff --git a/backend/app/nodes/albumentations_aug.py b/backend/app/nodes/albumentations_aug.py
new file mode 100644
index 0000000..e9f939c
--- /dev/null
+++ b/backend/app/nodes/albumentations_aug.py
@@ -0,0 +1,463 @@
+"""Catalog-driven Albumentations augment nodes with multi-target ports."""
+
+from __future__ import annotations
+
+from typing import Any
+
+import albumentations as A
+import cv2
+import numpy as np
+
+from app.engine.registry import BaseNode
+from app.models.graph import ParamField
+from app.nodes.albumentations_catalog import ALBUMENTATIONS_CATALOG, AlbuEntry, AlbuParam
+from app.nodes.common import (
+ bboxes_in,
+ bboxes_out,
+ image_in,
+ image_out,
+ keypoints_in,
+ keypoints_out,
+ mask_in,
+ mask_out,
+ require_image,
+)
+
+BORDER_MODE_MAP = {
+ "constant": cv2.BORDER_CONSTANT,
+ "replicate": cv2.BORDER_REPLICATE,
+ "reflect": cv2.BORDER_REFLECT,
+ "wrap": cv2.BORDER_WRAP,
+ "reflect101": cv2.BORDER_REFLECT_101,
+}
+
+AUGMENT_PORTS = [
+ image_in(),
+ mask_in(),
+ bboxes_in(),
+ keypoints_in(),
+ image_out(),
+ mask_out(),
+ bboxes_out(),
+ keypoints_out(),
+]
+
+
+def _param_field(param: AlbuParam) -> ParamField:
+ if param.kind == "boolean":
+ return ParamField(
+ name=param.name,
+ label=param.label,
+ type="select",
+ default="true" if param.default else "false",
+ options=["true", "false"],
+ description=param.description,
+ )
+ if param.kind == "range":
+ return ParamField(
+ name=param.name,
+ label=param.label,
+ type="number",
+ default=param.default,
+ minimum=param.minimum,
+ maximum=param.maximum,
+ step=param.step,
+ description=param.description,
+ )
+ if param.kind == "integer":
+ field_type = "integer"
+ elif param.kind == "select":
+ field_type = "select"
+ else:
+ field_type = "number"
+ return ParamField(
+ name=param.name,
+ label=param.label,
+ type=field_type,
+ default=param.default,
+ minimum=param.minimum,
+ maximum=param.maximum,
+ step=param.step if param.kind != "integer" else 1,
+ options=list(param.options) if param.options else None,
+ description=param.description,
+ )
+
+
+def _coerce_bool(value: Any) -> bool:
+ if isinstance(value, bool):
+ return value
+ return str(value).lower() in {"1", "true", "yes", "on"}
+
+
+def _build_kwargs(entry: AlbuEntry, params: dict[str, Any]) -> dict[str, Any]:
+ """Map inspector params into Albumentations transform kwargs."""
+ by_name = {param.name: param for param in entry.params}
+ assembled: dict[str, Any] = {}
+ consumed: set[str] = set()
+
+ def take(*names: str) -> None:
+ consumed.update(names)
+
+ if entry.class_name == "CLAHE" and "tile_grid_size" in params:
+ size = int(params["tile_grid_size"])
+ assembled["tile_grid_size"] = (size, size)
+ take("tile_grid_size")
+ elif entry.class_name == "GaussNoise":
+ assembled["std_range"] = (float(params["std_min"]), float(params["std_max"]))
+ take("std_min", "std_max")
+ elif entry.class_name == "ISONoise":
+ assembled["color_shift"] = (
+ float(params["color_shift_min"]),
+ float(params["color_shift_max"]),
+ )
+ assembled["intensity"] = (
+ float(params["intensity_min"]),
+ float(params["intensity_max"]),
+ )
+ take(
+ "color_shift_min",
+ "color_shift_max",
+ "intensity_min",
+ "intensity_max",
+ )
+ elif entry.class_name == "MultiplicativeNoise":
+ assembled["multiplier"] = (
+ float(params["multiplier_min"]),
+ float(params["multiplier_max"]),
+ )
+ take("multiplier_min", "multiplier_max")
+ elif entry.class_name == "SaltAndPepper":
+ assembled["amount"] = (float(params["amount_min"]), float(params["amount_max"]))
+ assembled["salt_vs_pepper"] = (
+ float(params["salt_min"]),
+ float(params["salt_max"]),
+ )
+ take("amount_min", "amount_max", "salt_min", "salt_max")
+ elif entry.class_name == "ImageCompression":
+ assembled["quality_range"] = (
+ int(params["quality_lower"]),
+ int(params["quality_upper"]),
+ )
+ assembled["compression_type"] = str(params.get("compression_type", "jpeg"))
+ take("quality_lower", "quality_upper", "compression_type")
+ elif entry.class_name == "Downscale":
+ assembled["scale_range"] = (float(params["scale_min"]), float(params["scale_max"]))
+ take("scale_min", "scale_max")
+ elif entry.class_name == "ChannelDropout":
+ assembled["channel_drop_range"] = (
+ int(params["channel_drop_min"]),
+ int(params["channel_drop_max"]),
+ )
+ assembled["fill"] = float(params["fill"])
+ take("channel_drop_min", "channel_drop_max", "fill")
+ elif entry.class_name == "Normalize":
+ assembled["mean"] = (
+ float(params["mean_r"]),
+ float(params["mean_g"]),
+ float(params["mean_b"]),
+ )
+ assembled["std"] = (
+ float(params["std_r"]),
+ float(params["std_g"]),
+ float(params["std_b"]),
+ )
+ assembled["max_pixel_value"] = float(params["max_pixel_value"])
+ take(
+ "mean_r",
+ "mean_g",
+ "mean_b",
+ "std_r",
+ "std_g",
+ "std_b",
+ "max_pixel_value",
+ )
+ elif entry.class_name == "CoarseDropout":
+ assembled["num_holes_range"] = (
+ int(params["num_holes_min"]),
+ int(params["num_holes_max"]),
+ )
+ assembled["hole_height_range"] = (
+ float(params["hole_height_min"]),
+ float(params["hole_height_max"]),
+ )
+ assembled["hole_width_range"] = (
+ float(params["hole_width_min"]),
+ float(params["hole_width_max"]),
+ )
+ take(
+ "num_holes_min",
+ "num_holes_max",
+ "hole_height_min",
+ "hole_height_max",
+ "hole_width_min",
+ "hole_width_max",
+ )
+ elif entry.class_name == "RandomFog":
+ assembled["fog_coef_range"] = (
+ float(params["fog_coef_min"]),
+ float(params["fog_coef_max"]),
+ )
+ take("fog_coef_min", "fog_coef_max")
+ elif entry.class_name == "RandomGamma":
+ assembled["gamma_limit"] = (
+ float(params["gamma_min"]),
+ float(params["gamma_max"]),
+ )
+ take("gamma_min", "gamma_max")
+ elif entry.class_name == "Solarize":
+ assembled["threshold_range"] = (
+ float(params["threshold_min"]),
+ float(params["threshold_max"]),
+ )
+ take("threshold_min", "threshold_max")
+ elif entry.class_name == "Sharpen":
+ assembled["alpha"] = (float(params["alpha_min"]), float(params["alpha_max"]))
+ assembled["lightness"] = (
+ float(params["lightness_min"]),
+ float(params["lightness_max"]),
+ )
+ take("alpha_min", "alpha_max", "lightness_min", "lightness_max")
+ elif entry.class_name == "Emboss":
+ assembled["alpha"] = (float(params["alpha_min"]), float(params["alpha_max"]))
+ assembled["strength"] = (
+ float(params["strength_min"]),
+ float(params["strength_max"]),
+ )
+ take("alpha_min", "alpha_max", "strength_min", "strength_max")
+ elif entry.class_name == "Affine":
+ assembled["scale"] = float(params["scale"])
+ assembled["translate_percent"] = float(params["translate_percent"])
+ assembled["rotate"] = float(params["rotate"])
+ assembled["shear"] = float(params["shear"])
+ take("scale", "translate_percent", "rotate", "shear")
+
+ kwargs: dict[str, Any] = dict(assembled)
+ for name, value in params.items():
+ if name in consumed:
+ continue
+ spec = by_name.get(name)
+ if spec is None:
+ continue
+ key = spec.albu_key or name
+ if key == "border_mode":
+ kwargs[key] = BORDER_MODE_MAP.get(str(value), cv2.BORDER_CONSTANT)
+ elif spec.kind == "boolean":
+ kwargs[key] = _coerce_bool(value)
+ elif spec.kind == "range":
+ magnitude = float(value)
+ kwargs[key] = (-magnitude, magnitude)
+ elif spec.kind == "integer":
+ kwargs[key] = int(value)
+ elif spec.kind == "select":
+ kwargs[key] = value
+ else:
+ kwargs[key] = float(value) if not isinstance(value, str) else value
+ return kwargs
+
+
+def _split_bboxes(raw: Any) -> tuple[list[list[float]], list[str]]:
+ if raw is None:
+ return [], []
+ if not isinstance(raw, list):
+ raise ValueError("bboxes input must be a list of [x_min, y_min, x_max, y_max, label?]")
+ boxes: list[list[float]] = []
+ labels: list[str] = []
+ for item in raw:
+ if not isinstance(item, (list, tuple)) or len(item) < 4:
+ raise ValueError(f"Invalid bbox entry: {item!r}")
+ boxes.append([float(item[0]), float(item[1]), float(item[2]), float(item[3])])
+ labels.append(str(item[4]) if len(item) >= 5 else "object")
+ return boxes, labels
+
+
+def _join_bboxes(boxes: Any, labels: Any) -> list[list[Any]]:
+ result: list[list[Any]] = []
+ label_list = list(labels) if labels is not None else []
+ for index, box in enumerate(boxes or []):
+ coords = [float(box[0]), float(box[1]), float(box[2]), float(box[3])]
+ label = label_list[index] if index < len(label_list) else "object"
+ result.append([*coords, label])
+ return result
+
+
+def _normalize_keypoints(raw: Any) -> list[list[float]]:
+ if raw is None:
+ return []
+ if not isinstance(raw, list):
+ raise ValueError("keypoints input must be a list of [x, y, ...]")
+ points: list[list[float]] = []
+ for item in raw:
+ if not isinstance(item, (list, tuple)) or len(item) < 2:
+ raise ValueError(f"Invalid keypoint entry: {item!r}")
+ points.append([float(item[0]), float(item[1])])
+ return points
+
+
+def _to_uint8_image(image: np.ndarray) -> np.ndarray:
+ if image.dtype == np.uint8:
+ return image
+ arr = image.astype(np.float32)
+ finite = arr[np.isfinite(arr)]
+ if finite.size == 0:
+ return np.zeros(image.shape, dtype=np.uint8)
+ lo, hi = float(finite.min()), float(finite.max())
+ if hi - lo < 1e-8:
+ scaled = np.zeros_like(arr)
+ else:
+ scaled = (arr - lo) / (hi - lo) * 255.0
+ return np.clip(scaled, 0, 255).astype(np.uint8)
+
+
+def _prepare_mask(mask: Any) -> np.ndarray | None:
+ if mask is None:
+ return None
+ if isinstance(mask, list):
+ if not mask:
+ return None
+ mask = mask[0]
+ if not isinstance(mask, np.ndarray):
+ raise ValueError("mask input must be an image array")
+ if mask.ndim == 3 and mask.shape[2] > 1:
+ return cv2.cvtColor(mask, cv2.COLOR_BGR2GRAY)
+ if mask.ndim == 3 and mask.shape[2] == 1:
+ return mask[:, :, 0]
+ return mask
+
+
+def run_albumentations(
+ entry: AlbuEntry,
+ inputs: dict[str, Any],
+ params: dict[str, Any],
+ seed: int,
+) -> dict[str, Any]:
+ image = require_image(inputs)
+ # Albumentations expects RGB; Image Pipes uses BGR OpenCV convention.
+ rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) if image.ndim == 3 else image
+
+ kwargs = _build_kwargs(entry, params)
+ transform_cls = getattr(A, entry.class_name)
+ transform = transform_cls(**kwargs)
+
+ has_mask = inputs.get("mask") is not None
+ has_bboxes = inputs.get("bboxes") is not None
+ has_keypoints = inputs.get("keypoints") is not None
+
+ bbox_params = None
+ keypoint_params = None
+ boxes: list[list[float]] = []
+ labels: list[str] = []
+ keypoints: list[list[float]] = []
+
+ if has_bboxes:
+ boxes, labels = _split_bboxes(inputs.get("bboxes"))
+ bbox_params = A.BboxParams(format="pascal_voc", label_fields=["bbox_labels"])
+ if has_keypoints:
+ keypoints = _normalize_keypoints(inputs.get("keypoints"))
+ keypoint_params = A.KeypointParams(format="xy", remove_invisible=False)
+
+ compose = A.Compose(
+ [transform],
+ bbox_params=bbox_params,
+ keypoint_params=keypoint_params,
+ seed=seed,
+ )
+
+ call: dict[str, Any] = {"image": rgb}
+ mask = _prepare_mask(inputs.get("mask")) if has_mask else None
+ if mask is not None:
+ call["mask"] = mask
+ if has_bboxes:
+ call["bboxes"] = boxes
+ call["bbox_labels"] = labels
+ if has_keypoints:
+ call["keypoints"] = keypoints
+
+ out = compose(**call)
+
+ out_image = out["image"]
+ if out_image.ndim == 3:
+ out_image = cv2.cvtColor(_to_uint8_image(out_image), cv2.COLOR_RGB2BGR)
+ else:
+ out_image = _to_uint8_image(out_image)
+
+ result: dict[str, Any] = {"image": out_image}
+ if has_mask and "mask" in out:
+ result["mask"] = out["mask"]
+ if has_bboxes:
+ result["bboxes"] = _join_bboxes(out.get("bboxes", []), out.get("bbox_labels", labels))
+ if has_keypoints:
+ result["keypoints"] = [
+ [float(pt[0]), float(pt[1])] for pt in out.get("keypoints", [])
+ ]
+ return result
+
+
+def _emit_python_lines(
+ entry: AlbuEntry,
+ params: dict[str, Any],
+ input_vars: dict[str, str],
+ output_vars: dict[str, str],
+) -> list[str]:
+ kwargs = _build_kwargs(entry, params)
+ kwargs_repr = ", ".join(f"{key}={value!r}" for key, value in sorted(kwargs.items()))
+ src = input_vars.get("image", "image")
+ dst = output_vars.get("image", "image")
+ lines = [
+ "import albumentations as A",
+ f"_rgb = cv2.cvtColor({src}, cv2.COLOR_BGR2RGB) if {src}.ndim == 3 else {src}",
+ f"_tf = A.Compose([A.{entry.class_name}({kwargs_repr})], seed=seed)",
+ "_out = _tf(image=_rgb)",
+ "_img = _out['image']",
+ f"{dst} = cv2.cvtColor(_img, cv2.COLOR_RGB2BGR) if _img.ndim == 3 else _img",
+ ]
+ if "mask" in output_vars and "mask" in input_vars:
+ lines.append(f"{output_vars['mask']} = _out.get('mask', {input_vars['mask']})")
+ if "bboxes" in output_vars:
+ lines.append(f"{output_vars['bboxes']} = _out.get('bboxes', [])")
+ if "keypoints" in output_vars:
+ lines.append(f"{output_vars['keypoints']} = _out.get('keypoints', [])")
+ return lines
+
+
+def _make_node_class(entry: AlbuEntry) -> type[BaseNode]:
+ class_name = f"{entry.class_name}AugNode"
+
+ def execute(
+ self: BaseNode,
+ inputs: dict[str, Any],
+ params: dict[str, Any],
+ seed: int = 0,
+ ) -> dict[str, Any]:
+ return run_albumentations(entry, inputs, params, seed)
+
+ def emit_python(
+ self: BaseNode,
+ node_id: str,
+ params: dict[str, Any],
+ input_vars: dict[str, str],
+ output_vars: dict[str, str],
+ ) -> list[str]:
+ return _emit_python_lines(entry, params, input_vars, output_vars)
+
+ attrs: dict[str, Any] = {
+ "type": entry.node_type,
+ "label": entry.label,
+ "category": "augment",
+ "description": f"[{entry.family}] {entry.description}",
+ "ports": list(AUGMENT_PORTS),
+ "params": [_param_field(param) for param in entry.params],
+ "stochastic": True,
+ "execute": execute,
+ "emit_python": emit_python,
+ }
+ return type(class_name, (BaseNode,), attrs)
+
+
+def build_albumentations_nodes() -> list[BaseNode]:
+ nodes: list[BaseNode] = []
+ for entry in ALBUMENTATIONS_CATALOG:
+ if not hasattr(A, entry.class_name):
+ continue
+ node_cls = _make_node_class(entry)
+ nodes.append(node_cls())
+ return nodes
diff --git a/backend/app/nodes/albumentations_catalog.py b/backend/app/nodes/albumentations_catalog.py
new file mode 100644
index 0000000..82e9045
--- /dev/null
+++ b/backend/app/nodes/albumentations_catalog.py
@@ -0,0 +1,1062 @@
+"""Catalog of Albumentations transforms exposed as Image Pipes nodes."""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+from typing import Any, Literal
+
+
+@dataclass(frozen=True)
+class AlbuParam:
+ name: str
+ label: str
+ kind: Literal["number", "integer", "select", "boolean", "range"]
+ default: Any
+ minimum: float | None = None
+ maximum: float | None = None
+ step: float | None = None
+ options: tuple[str, ...] | None = None
+ description: str | None = None
+ # When set, maps UI value into transform kwargs under this key.
+ albu_key: str | None = None
+
+
+@dataclass(frozen=True)
+class AlbuEntry:
+ class_name: str
+ node_type: str
+ label: str
+ family: str
+ targets: Literal["image_only", "dual"]
+ description: str
+ params: tuple[AlbuParam, ...] = field(default_factory=tuple)
+
+
+def _p(default: float = 0.5) -> AlbuParam:
+ return AlbuParam(
+ "p",
+ "Probability",
+ "number",
+ default,
+ minimum=0.0,
+ maximum=1.0,
+ step=0.05,
+ description="Chance the transform is applied",
+ )
+
+
+def _range(
+ name: str,
+ label: str,
+ default: float,
+ minimum: float = 0.0,
+ maximum: float = 1.0,
+ step: float = 0.01,
+ description: str | None = None,
+ albu_key: str | None = None,
+) -> AlbuParam:
+ return AlbuParam(
+ name,
+ label,
+ "range",
+ default,
+ minimum=minimum,
+ maximum=maximum,
+ step=step,
+ description=description or f"Symmetric limit → (-v, +v) for {albu_key or name}",
+ albu_key=albu_key or name,
+ )
+
+
+def _num(
+ name: str,
+ label: str,
+ default: float,
+ minimum: float | None = None,
+ maximum: float | None = None,
+ step: float | None = 0.01,
+ description: str | None = None,
+ albu_key: str | None = None,
+) -> AlbuParam:
+ return AlbuParam(
+ name,
+ label,
+ "number",
+ default,
+ minimum=minimum,
+ maximum=maximum,
+ step=step,
+ description=description,
+ albu_key=albu_key,
+ )
+
+
+def _int(
+ name: str,
+ label: str,
+ default: int,
+ minimum: int | None = None,
+ maximum: int | None = None,
+ description: str | None = None,
+ albu_key: str | None = None,
+) -> AlbuParam:
+ return AlbuParam(
+ name,
+ label,
+ "integer",
+ default,
+ minimum=minimum,
+ maximum=maximum,
+ step=1,
+ description=description,
+ albu_key=albu_key,
+ )
+
+
+def _sel(
+ name: str,
+ label: str,
+ default: str,
+ options: tuple[str, ...],
+ description: str | None = None,
+ albu_key: str | None = None,
+) -> AlbuParam:
+ return AlbuParam(
+ name,
+ label,
+ "select",
+ default,
+ options=options,
+ description=description,
+ albu_key=albu_key,
+ )
+
+
+def _bool(
+ name: str,
+ label: str,
+ default: bool,
+ description: str | None = None,
+ albu_key: str | None = None,
+) -> AlbuParam:
+ return AlbuParam(
+ name,
+ label,
+ "boolean",
+ default,
+ description=description,
+ albu_key=albu_key,
+ )
+
+
+# ---------------------------------------------------------------------------
+# Color / pixel (ImageOnly)
+# ---------------------------------------------------------------------------
+COLOR_ENTRIES: tuple[AlbuEntry, ...] = (
+ AlbuEntry(
+ "RandomBrightnessContrast",
+ "albu_random_brightness_contrast",
+ "Albu Brightness/Contrast",
+ "color",
+ "image_only",
+ "Random brightness and contrast jitter (Albumentations).",
+ (
+ _range("brightness_limit", "Brightness Limit", 0.2, 0.0, 1.0),
+ _range("contrast_limit", "Contrast Limit", 0.2, 0.0, 1.0),
+ _bool("brightness_by_max", "Brightness By Max", True),
+ _p(),
+ ),
+ ),
+ AlbuEntry(
+ "HueSaturationValue",
+ "albu_hue_saturation_value",
+ "Albu Hue/Saturation/Value",
+ "color",
+ "image_only",
+ "Random HSV shifts.",
+ (
+ _range("hue_shift_limit", "Hue Shift", 20, 0, 100, 1),
+ _range("sat_shift_limit", "Saturation Shift", 30, 0, 100, 1),
+ _range("val_shift_limit", "Value Shift", 20, 0, 100, 1),
+ _p(),
+ ),
+ ),
+ AlbuEntry(
+ "RGBShift",
+ "albu_rgb_shift",
+ "Albu RGB Shift",
+ "color",
+ "image_only",
+ "Independently shift R/G/B channels.",
+ (
+ _range("r_shift_limit", "R Shift", 20, 0, 100, 1),
+ _range("g_shift_limit", "G Shift", 20, 0, 100, 1),
+ _range("b_shift_limit", "B Shift", 20, 0, 100, 1),
+ _p(),
+ ),
+ ),
+ AlbuEntry(
+ "ColorJitter",
+ "albu_color_jitter",
+ "Albu Color Jitter",
+ "color",
+ "image_only",
+ "Jitter brightness, contrast, saturation, and hue.",
+ (
+ _num("brightness", "Brightness", 0.2, 0.0, 1.0, 0.01),
+ _num("contrast", "Contrast", 0.2, 0.0, 1.0, 0.01),
+ _num("saturation", "Saturation", 0.2, 0.0, 1.0, 0.01),
+ _num("hue", "Hue", 0.1, 0.0, 0.5, 0.01),
+ _p(),
+ ),
+ ),
+ AlbuEntry(
+ "CLAHE",
+ "albu_clahe",
+ "Albu CLAHE",
+ "color",
+ "image_only",
+ "Contrast Limited Adaptive Histogram Equalization.",
+ (
+ _num("clip_limit", "Clip Limit", 4.0, 1.0, 40.0, 0.5),
+ _int("tile_grid_size", "Tile Grid Size", 8, 1, 32, "Square tile grid size"),
+ _p(),
+ ),
+ ),
+ AlbuEntry(
+ "Equalize",
+ "albu_equalize",
+ "Albu Equalize",
+ "color",
+ "image_only",
+ "Histogram equalization.",
+ (
+ _sel("mode", "Mode", "cv", ("cv", "pil")),
+ _bool("by_channels", "By Channels", True),
+ _p(),
+ ),
+ ),
+ AlbuEntry(
+ "RandomGamma",
+ "albu_random_gamma",
+ "Albu Random Gamma",
+ "color",
+ "image_only",
+ "Apply a random gamma transform.",
+ (
+ _num("gamma_min", "Gamma Min", 80, 10, 200, 1),
+ _num("gamma_max", "Gamma Max", 120, 10, 200, 1),
+ _p(),
+ ),
+ ),
+ AlbuEntry(
+ "RandomToneCurve",
+ "albu_random_tone_curve",
+ "Albu Random Tone Curve",
+ "color",
+ "image_only",
+ "Random tone curve adjustment.",
+ (_num("scale", "Scale", 0.1, 0.0, 1.0, 0.01), _p()),
+ ),
+ AlbuEntry(
+ "Posterize",
+ "albu_posterize",
+ "Albu Posterize",
+ "color",
+ "image_only",
+ "Reduce the number of bits per channel.",
+ (_int("num_bits", "Num Bits", 4, 1, 8), _p()),
+ ),
+ AlbuEntry(
+ "Solarize",
+ "albu_solarize",
+ "Albu Solarize",
+ "color",
+ "image_only",
+ "Invert all pixels above a threshold.",
+ (
+ _num("threshold_min", "Threshold Min", 0.5, 0.0, 1.0, 0.05),
+ _num("threshold_max", "Threshold Max", 0.5, 0.0, 1.0, 0.05),
+ _p(),
+ ),
+ ),
+ AlbuEntry(
+ "InvertImg",
+ "albu_invert_img",
+ "Albu Invert",
+ "color",
+ "image_only",
+ "Invert image pixel values.",
+ (_p(1.0),),
+ ),
+ AlbuEntry(
+ "ToGray",
+ "albu_to_gray",
+ "Albu To Gray",
+ "color",
+ "image_only",
+ "Convert image to grayscale (kept as 3-channel by Albumentations).",
+ (_p(1.0),),
+ ),
+ AlbuEntry(
+ "ToSepia",
+ "albu_to_sepia",
+ "Albu To Sepia",
+ "color",
+ "image_only",
+ "Apply a sepia filter.",
+ (_p(1.0),),
+ ),
+ AlbuEntry(
+ "ToRGB",
+ "albu_to_rgb",
+ "Albu To RGB",
+ "color",
+ "image_only",
+ "Convert grayscale to RGB.",
+ (_p(1.0),),
+ ),
+ AlbuEntry(
+ "FancyPCA",
+ "albu_fancy_pca",
+ "Albu Fancy PCA",
+ "color",
+ "image_only",
+ "PCA color augmentation (Krizhevsky-style).",
+ (_num("alpha", "Alpha", 0.1, 0.0, 1.0, 0.01), _p()),
+ ),
+ AlbuEntry(
+ "PlanckianJitter",
+ "albu_planckian_jitter",
+ "Albu Planckian Jitter",
+ "color",
+ "image_only",
+ "Physically based color temperature jitter.",
+ (
+ _sel("mode", "Mode", "blackbody", ("blackbody", "cietype")),
+ _p(),
+ ),
+ ),
+ AlbuEntry(
+ "Sharpen",
+ "albu_sharpen",
+ "Albu Sharpen",
+ "color",
+ "image_only",
+ "Sharpen the input image.",
+ (
+ _num("alpha_min", "Alpha Min", 0.2, 0.0, 1.0, 0.05),
+ _num("alpha_max", "Alpha Max", 0.5, 0.0, 1.0, 0.05),
+ _num("lightness_min", "Lightness Min", 0.5, 0.0, 1.0, 0.05),
+ _num("lightness_max", "Lightness Max", 1.0, 0.0, 1.0, 0.05),
+ _p(),
+ ),
+ ),
+ AlbuEntry(
+ "Emboss",
+ "albu_emboss",
+ "Albu Emboss",
+ "color",
+ "image_only",
+ "Emboss the input image.",
+ (
+ _num("alpha_min", "Alpha Min", 0.2, 0.0, 1.0, 0.05),
+ _num("alpha_max", "Alpha Max", 0.5, 0.0, 1.0, 0.05),
+ _num("strength_min", "Strength Min", 0.2, 0.0, 1.0, 0.05),
+ _num("strength_max", "Strength Max", 0.7, 0.0, 1.0, 0.05),
+ _p(),
+ ),
+ ),
+ AlbuEntry(
+ "AutoContrast",
+ "albu_auto_contrast",
+ "Albu Auto Contrast",
+ "color",
+ "image_only",
+ "Maximize image contrast.",
+ (_p(1.0),),
+ ),
+)
+
+
+# ---------------------------------------------------------------------------
+# Blur / noise (ImageOnly)
+# ---------------------------------------------------------------------------
+BLUR_NOISE_ENTRIES: tuple[AlbuEntry, ...] = (
+ AlbuEntry(
+ "Blur",
+ "albu_blur",
+ "Albu Blur",
+ "blur",
+ "image_only",
+ "Random blur with a square kernel.",
+ (_int("blur_limit", "Blur Limit", 7, 3, 15), _p()),
+ ),
+ AlbuEntry(
+ "GaussianBlur",
+ "albu_gaussian_blur",
+ "Albu Gaussian Blur",
+ "blur",
+ "image_only",
+ "Apply Gaussian blur.",
+ (_int("blur_limit", "Blur Limit", 7, 3, 15), _p()),
+ ),
+ AlbuEntry(
+ "MotionBlur",
+ "albu_motion_blur",
+ "Albu Motion Blur",
+ "blur",
+ "image_only",
+ "Apply motion blur.",
+ (_int("blur_limit", "Blur Limit", 7, 3, 15), _p()),
+ ),
+ AlbuEntry(
+ "MedianBlur",
+ "albu_median_blur",
+ "Albu Median Blur",
+ "blur",
+ "image_only",
+ "Apply median blur.",
+ (_int("blur_limit", "Blur Limit", 7, 3, 15), _p()),
+ ),
+ AlbuEntry(
+ "GlassBlur",
+ "albu_glass_blur",
+ "Albu Glass Blur",
+ "blur",
+ "image_only",
+ "Glass blur distortion.",
+ (
+ _num("sigma", "Sigma", 0.7, 0.0, 2.0, 0.05),
+ _num("max_delta", "Max Delta", 4, 1, 10, 1),
+ _int("iterations", "Iterations", 2, 1, 5),
+ _p(),
+ ),
+ ),
+ AlbuEntry(
+ "AdvancedBlur",
+ "albu_advanced_blur",
+ "Albu Advanced Blur",
+ "blur",
+ "image_only",
+ "Generalized blur with random kernels.",
+ (_p(),),
+ ),
+ AlbuEntry(
+ "Defocus",
+ "albu_defocus",
+ "Albu Defocus",
+ "blur",
+ "image_only",
+ "Simulate defocus blur.",
+ (
+ _int("radius", "Radius", 3, 1, 10),
+ _num("alias_blur", "Alias Blur", 0.1, 0.0, 1.0, 0.05),
+ _p(),
+ ),
+ ),
+ AlbuEntry(
+ "ZoomBlur",
+ "albu_zoom_blur",
+ "Albu Zoom Blur",
+ "blur",
+ "image_only",
+ "Apply zoom blur.",
+ (_p(),),
+ ),
+ AlbuEntry(
+ "GaussNoise",
+ "albu_gauss_noise",
+ "Albu Gauss Noise",
+ "noise",
+ "image_only",
+ "Apply Gaussian noise.",
+ (
+ _num("std_min", "Std Min", 0.2, 0.0, 1.0, 0.01, albu_key="std_range"),
+ _num("std_max", "Std Max", 0.44, 0.0, 1.0, 0.01, albu_key="std_range"),
+ _bool("per_channel", "Per Channel", True),
+ _p(),
+ ),
+ ),
+ AlbuEntry(
+ "ISONoise",
+ "albu_iso_noise",
+ "Albu ISO Noise",
+ "noise",
+ "image_only",
+ "Apply camera ISO-like noise.",
+ (
+ _num("color_shift_min", "Color Shift Min", 0.01, 0.0, 1.0, 0.01),
+ _num("color_shift_max", "Color Shift Max", 0.05, 0.0, 1.0, 0.01),
+ _num("intensity_min", "Intensity Min", 0.1, 0.0, 1.0, 0.01),
+ _num("intensity_max", "Intensity Max", 0.5, 0.0, 1.0, 0.01),
+ _p(),
+ ),
+ ),
+ AlbuEntry(
+ "MultiplicativeNoise",
+ "albu_multiplicative_noise",
+ "Albu Multiplicative Noise",
+ "noise",
+ "image_only",
+ "Multiply image by random noise.",
+ (
+ _num("multiplier_min", "Multiplier Min", 0.9, 0.1, 2.0, 0.01),
+ _num("multiplier_max", "Multiplier Max", 1.1, 0.1, 2.0, 0.01),
+ _bool("per_channel", "Per Channel", True),
+ _p(),
+ ),
+ ),
+ AlbuEntry(
+ "SaltAndPepper",
+ "albu_salt_and_pepper",
+ "Albu Salt And Pepper",
+ "noise",
+ "image_only",
+ "Add salt-and-pepper noise.",
+ (
+ _num("amount_min", "Amount Min", 0.01, 0.0, 0.5, 0.01),
+ _num("amount_max", "Amount Max", 0.06, 0.0, 0.5, 0.01),
+ _num("salt_min", "Salt Ratio Min", 0.4, 0.0, 1.0, 0.05),
+ _num("salt_max", "Salt Ratio Max", 0.6, 0.0, 1.0, 0.05),
+ _p(),
+ ),
+ ),
+ AlbuEntry(
+ "ImageCompression",
+ "albu_image_compression",
+ "Albu Image Compression",
+ "noise",
+ "image_only",
+ "Simulate JPEG/WebP compression artifacts.",
+ (
+ _int("quality_lower", "Quality Lower", 50, 1, 100),
+ _int("quality_upper", "Quality Upper", 100, 1, 100),
+ _sel(
+ "compression_type",
+ "Compression Type",
+ "jpeg",
+ ("jpeg", "webp"),
+ ),
+ _p(),
+ ),
+ ),
+ AlbuEntry(
+ "Downscale",
+ "albu_downscale",
+ "Albu Downscale",
+ "noise",
+ "image_only",
+ "Downscale then upscale to degrade resolution.",
+ (
+ _num("scale_min", "Scale Min", 0.25, 0.05, 1.0, 0.05),
+ _num("scale_max", "Scale Max", 0.5, 0.05, 1.0, 0.05),
+ _p(),
+ ),
+ ),
+ AlbuEntry(
+ "RingingOvershoot",
+ "albu_ringing_overshoot",
+ "Albu Ringing Overshoot",
+ "noise",
+ "image_only",
+ "Simulate ringing / overshoot artifacts.",
+ (_p(),),
+ ),
+)
+
+
+# ---------------------------------------------------------------------------
+# Weather / illumination (ImageOnly)
+# ---------------------------------------------------------------------------
+WEATHER_ENTRIES: tuple[AlbuEntry, ...] = (
+ AlbuEntry(
+ "RandomFog",
+ "albu_random_fog",
+ "Albu Random Fog",
+ "weather",
+ "image_only",
+ "Add fog to the image.",
+ (
+ _num("fog_coef_min", "Fog Coef Min", 0.3, 0.0, 1.0, 0.05),
+ _num("fog_coef_max", "Fog Coef Max", 1.0, 0.0, 1.0, 0.05),
+ _num("alpha_coef", "Alpha Coef", 0.08, 0.0, 1.0, 0.01),
+ _p(),
+ ),
+ ),
+ AlbuEntry(
+ "RandomRain",
+ "albu_random_rain",
+ "Albu Random Rain",
+ "weather",
+ "image_only",
+ "Add rain streaks.",
+ (_p(),),
+ ),
+ AlbuEntry(
+ "RandomSnow",
+ "albu_random_snow",
+ "Albu Random Snow",
+ "weather",
+ "image_only",
+ "Add snow.",
+ (_p(),),
+ ),
+ AlbuEntry(
+ "RandomSunFlare",
+ "albu_random_sun_flare",
+ "Albu Random Sun Flare",
+ "weather",
+ "image_only",
+ "Add a sun flare effect.",
+ (_p(),),
+ ),
+ AlbuEntry(
+ "RandomShadow",
+ "albu_random_shadow",
+ "Albu Random Shadow",
+ "weather",
+ "image_only",
+ "Add random shadows.",
+ (_p(),),
+ ),
+ AlbuEntry(
+ "RandomGravel",
+ "albu_random_gravel",
+ "Albu Random Gravel",
+ "weather",
+ "image_only",
+ "Add gravel-like noise patches.",
+ (_p(),),
+ ),
+ AlbuEntry(
+ "Spatter",
+ "albu_spatter",
+ "Albu Spatter",
+ "weather",
+ "image_only",
+ "Simulate rain / mud spatter.",
+ (_p(),),
+ ),
+ AlbuEntry(
+ "Illumination",
+ "albu_illumination",
+ "Albu Illumination",
+ "weather",
+ "image_only",
+ "Non-uniform illumination change.",
+ (_p(),),
+ ),
+ AlbuEntry(
+ "PlasmaBrightnessContrast",
+ "albu_plasma_brightness_contrast",
+ "Albu Plasma Brightness/Contrast",
+ "weather",
+ "image_only",
+ "Plasma-noise based brightness/contrast.",
+ (_p(),),
+ ),
+ AlbuEntry(
+ "PlasmaShadow",
+ "albu_plasma_shadow",
+ "Albu Plasma Shadow",
+ "weather",
+ "image_only",
+ "Plasma-noise based shadows.",
+ (_p(),),
+ ),
+ AlbuEntry(
+ "ChromaticAberration",
+ "albu_chromatic_aberration",
+ "Albu Chromatic Aberration",
+ "weather",
+ "image_only",
+ "Simulate chromatic aberration.",
+ (_p(),),
+ ),
+)
+
+
+# ---------------------------------------------------------------------------
+# Normalize / channels / dropout (ImageOnly)
+# ---------------------------------------------------------------------------
+NORMALIZE_CHANNEL_ENTRIES: tuple[AlbuEntry, ...] = (
+ AlbuEntry(
+ "Normalize",
+ "albu_normalize",
+ "Albu Normalize",
+ "normalize",
+ "image_only",
+ "Normalize pixels (float). Remapped to uint8 for previews.",
+ (
+ _num("mean_r", "Mean R", 0.485, 0.0, 1.0, 0.001),
+ _num("mean_g", "Mean G", 0.456, 0.0, 1.0, 0.001),
+ _num("mean_b", "Mean B", 0.406, 0.0, 1.0, 0.001),
+ _num("std_r", "Std R", 0.229, 0.0, 1.0, 0.001),
+ _num("std_g", "Std G", 0.224, 0.0, 1.0, 0.001),
+ _num("std_b", "Std B", 0.225, 0.0, 1.0, 0.001),
+ _num("max_pixel_value", "Max Pixel Value", 255.0, 1.0, 255.0, 1.0),
+ _p(1.0),
+ ),
+ ),
+ AlbuEntry(
+ "ChannelShuffle",
+ "albu_channel_shuffle",
+ "Albu Channel Shuffle",
+ "channels",
+ "image_only",
+ "Randomly rearrange color channels.",
+ (_p(),),
+ ),
+ AlbuEntry(
+ "ChannelDropout",
+ "albu_channel_dropout",
+ "Albu Channel Dropout",
+ "channels",
+ "image_only",
+ "Drop random channels.",
+ (
+ _int("channel_drop_min", "Drop Min", 1, 1, 2),
+ _int("channel_drop_max", "Drop Max", 1, 1, 2),
+ _num("fill", "Fill Value", 0, 0, 255, 1),
+ _p(),
+ ),
+ ),
+ AlbuEntry(
+ "ToFloat",
+ "albu_to_float",
+ "Albu To Float",
+ "normalize",
+ "image_only",
+ "Divide by max_value (float). Remapped to uint8 for previews.",
+ (_num("max_value", "Max Value", 255.0, 1.0, 255.0, 1.0), _p(1.0)),
+ ),
+ AlbuEntry(
+ "FromFloat",
+ "albu_from_float",
+ "Albu From Float",
+ "normalize",
+ "image_only",
+ "Multiply float image back toward uint8 range.",
+ (_num("max_value", "Max Value", 255.0, 1.0, 255.0, 1.0), _p(1.0)),
+ ),
+ AlbuEntry(
+ "PixelDropout",
+ "albu_pixel_dropout",
+ "Albu Pixel Dropout",
+ "channels",
+ "image_only",
+ "Set random pixels to a fill value.",
+ (
+ _num("dropout_prob", "Dropout Prob", 0.01, 0.0, 1.0, 0.01),
+ _num("drop_value", "Drop Value", 0, 0, 255, 1),
+ _p(),
+ ),
+ ),
+ AlbuEntry(
+ "CoarseDropout",
+ "albu_coarse_dropout",
+ "Albu Coarse Dropout",
+ "channels",
+ "image_only",
+ "Drop rectangular regions (cutout-style).",
+ (
+ _int("num_holes_min", "Holes Min", 1, 1, 32),
+ _int("num_holes_max", "Holes Max", 8, 1, 32),
+ _num("hole_height_min", "Hole H Fraction Min", 0.1, 0.01, 1.0, 0.01),
+ _num("hole_height_max", "Hole H Fraction Max", 0.2, 0.01, 1.0, 0.01),
+ _num("hole_width_min", "Hole W Fraction Min", 0.1, 0.01, 1.0, 0.01),
+ _num("hole_width_max", "Hole W Fraction Max", 0.2, 0.01, 1.0, 0.01),
+ _p(),
+ ),
+ ),
+ AlbuEntry(
+ "Erasing",
+ "albu_erasing",
+ "Albu Erasing",
+ "channels",
+ "image_only",
+ "Random erasing augmentation.",
+ (_p(),),
+ ),
+ AlbuEntry(
+ "Superpixels",
+ "albu_superpixels",
+ "Albu Superpixels",
+ "channels",
+ "image_only",
+ "Approximate image with superpixels.",
+ (
+ _num("p_replace", "Replace Prob", 0.1, 0.0, 1.0, 0.05),
+ _int("n_segments", "N Segments", 100, 10, 500),
+ _p(),
+ ),
+ ),
+)
+
+
+# ---------------------------------------------------------------------------
+# Dual geometry (mask / bboxes / keypoints stay aligned)
+# ---------------------------------------------------------------------------
+DUAL_GEOMETRY_ENTRIES: tuple[AlbuEntry, ...] = (
+ AlbuEntry(
+ "HorizontalFlip",
+ "albu_horizontal_flip",
+ "Albu Horizontal Flip",
+ "geometry",
+ "dual",
+ "Flip horizontally (syncs mask, bboxes, keypoints).",
+ (_p(0.5),),
+ ),
+ AlbuEntry(
+ "VerticalFlip",
+ "albu_vertical_flip",
+ "Albu Vertical Flip",
+ "geometry",
+ "dual",
+ "Flip vertically (syncs mask, bboxes, keypoints).",
+ (_p(0.5),),
+ ),
+ AlbuEntry(
+ "RandomRotate90",
+ "albu_random_rotate90",
+ "Albu Random Rotate 90",
+ "geometry",
+ "dual",
+ "Rotate by a random multiple of 90°.",
+ (_p(1.0),),
+ ),
+ AlbuEntry(
+ "Transpose",
+ "albu_transpose",
+ "Albu Transpose",
+ "geometry",
+ "dual",
+ "Transpose the image (swap rows/cols).",
+ (_p(1.0),),
+ ),
+ AlbuEntry(
+ "D4",
+ "albu_d4",
+ "Albu D4",
+ "geometry",
+ "dual",
+ "Random D4 dihedral group transform.",
+ (_p(1.0),),
+ ),
+ AlbuEntry(
+ "Rotate",
+ "albu_rotate",
+ "Albu Rotate",
+ "geometry",
+ "dual",
+ "Rotate by a random angle.",
+ (
+ _num("limit", "Angle Limit", 45, 0, 180, 1),
+ _sel(
+ "border_mode",
+ "Border Mode",
+ "constant",
+ ("constant", "replicate", "reflect", "wrap", "reflect101"),
+ ),
+ _p(1.0),
+ ),
+ ),
+ AlbuEntry(
+ "SafeRotate",
+ "albu_safe_rotate",
+ "Albu Safe Rotate",
+ "geometry",
+ "dual",
+ "Rotate and resize to keep the full image.",
+ (_num("limit", "Angle Limit", 45, 0, 180, 1), _p(1.0)),
+ ),
+ AlbuEntry(
+ "Affine",
+ "albu_affine",
+ "Albu Affine",
+ "geometry",
+ "dual",
+ "Affine transform (scale / translate / rotate / shear).",
+ (
+ _num("scale", "Scale", 1.0, 0.5, 1.5, 0.05),
+ _num("translate_percent", "Translate %", 0.1, 0.0, 0.5, 0.01),
+ _num("rotate", "Rotate", 15, 0, 180, 1),
+ _num("shear", "Shear", 10, 0, 45, 1),
+ _p(1.0),
+ ),
+ ),
+ AlbuEntry(
+ "Perspective",
+ "albu_perspective",
+ "Albu Perspective",
+ "geometry",
+ "dual",
+ "Random perspective transform.",
+ (_num("scale", "Scale", 0.05, 0.01, 0.3, 0.01), _p(1.0)),
+ ),
+ AlbuEntry(
+ "ElasticTransform",
+ "albu_elastic_transform",
+ "Albu Elastic Transform",
+ "geometry",
+ "dual",
+ "Elastic deformation.",
+ (
+ _num("alpha", "Alpha", 1.0, 0.1, 50.0, 0.1),
+ _num("sigma", "Sigma", 50.0, 1.0, 100.0, 1.0),
+ _p(1.0),
+ ),
+ ),
+ AlbuEntry(
+ "GridDistortion",
+ "albu_grid_distortion",
+ "Albu Grid Distortion",
+ "geometry",
+ "dual",
+ "Grid-based distortion.",
+ (
+ _int("num_steps", "Num Steps", 5, 1, 20),
+ _num("distort_limit", "Distort Limit", 0.3, 0.0, 1.0, 0.05),
+ _p(1.0),
+ ),
+ ),
+ AlbuEntry(
+ "OpticalDistortion",
+ "albu_optical_distortion",
+ "Albu Optical Distortion",
+ "geometry",
+ "dual",
+ "Barrel / pincushion distortion.",
+ (
+ _num("distort_limit", "Distort Limit", 0.05, 0.0, 0.5, 0.01),
+ _p(1.0),
+ ),
+ ),
+ AlbuEntry(
+ "Resize",
+ "albu_resize",
+ "Albu Resize",
+ "geometry",
+ "dual",
+ "Resize to a fixed height/width.",
+ (
+ _int("height", "Height", 256, 8, 4096),
+ _int("width", "Width", 256, 8, 4096),
+ _p(1.0),
+ ),
+ ),
+ AlbuEntry(
+ "LongestMaxSize",
+ "albu_longest_max_size",
+ "Albu Longest Max Size",
+ "geometry",
+ "dual",
+ "Rescale so the longest side equals max_size.",
+ (_int("max_size", "Max Size", 512, 16, 4096), _p(1.0)),
+ ),
+ AlbuEntry(
+ "SmallestMaxSize",
+ "albu_smallest_max_size",
+ "Albu Smallest Max Size",
+ "geometry",
+ "dual",
+ "Rescale so the shortest side equals max_size.",
+ (_int("max_size", "Max Size", 512, 16, 4096), _p(1.0)),
+ ),
+ AlbuEntry(
+ "PadIfNeeded",
+ "albu_pad_if_needed",
+ "Albu Pad If Needed",
+ "geometry",
+ "dual",
+ "Pad to at least min height/width.",
+ (
+ _int("min_height", "Min Height", 256, 1, 4096),
+ _int("min_width", "Min Width", 256, 1, 4096),
+ _sel(
+ "border_mode",
+ "Border Mode",
+ "constant",
+ ("constant", "replicate", "reflect", "wrap", "reflect101"),
+ ),
+ _p(1.0),
+ ),
+ ),
+ AlbuEntry(
+ "CenterCrop",
+ "albu_center_crop",
+ "Albu Center Crop",
+ "geometry",
+ "dual",
+ "Crop the center of the image.",
+ (
+ _int("height", "Height", 128, 8, 4096),
+ _int("width", "Width", 128, 8, 4096),
+ _p(1.0),
+ ),
+ ),
+ AlbuEntry(
+ "RandomCrop",
+ "albu_random_crop",
+ "Albu Random Crop",
+ "geometry",
+ "dual",
+ "Crop a random region.",
+ (
+ _int("height", "Height", 128, 8, 4096),
+ _int("width", "Width", 128, 8, 4096),
+ _p(1.0),
+ ),
+ ),
+ AlbuEntry(
+ "Crop",
+ "albu_crop",
+ "Albu Crop",
+ "geometry",
+ "dual",
+ "Crop a fixed rectangle.",
+ (
+ _int("x_min", "X Min", 0, 0, 4096),
+ _int("y_min", "Y Min", 0, 0, 4096),
+ _int("x_max", "X Max", 128, 1, 4096),
+ _int("y_max", "Y Max", 128, 1, 4096),
+ _p(1.0),
+ ),
+ ),
+ AlbuEntry(
+ "RandomScale",
+ "albu_random_scale",
+ "Albu Random Scale",
+ "geometry",
+ "dual",
+ "Randomly rescale the image.",
+ (
+ _num("scale_limit", "Scale Limit", 0.1, 0.0, 1.0, 0.01),
+ _p(1.0),
+ ),
+ ),
+ AlbuEntry(
+ "ShiftScaleRotate",
+ "albu_shift_scale_rotate",
+ "Albu Shift Scale Rotate",
+ "geometry",
+ "dual",
+ "Combined shift / scale / rotate (legacy).",
+ (
+ _num("shift_limit", "Shift Limit", 0.0625, 0.0, 0.5, 0.01),
+ _num("scale_limit", "Scale Limit", 0.1, 0.0, 1.0, 0.01),
+ _num("rotate_limit", "Rotate Limit", 45, 0, 180, 1),
+ _p(1.0),
+ ),
+ ),
+)
+
+
+ALBUMENTATIONS_CATALOG: tuple[AlbuEntry, ...] = (
+ COLOR_ENTRIES
+ + BLUR_NOISE_ENTRIES
+ + WEATHER_ENTRIES
+ + NORMALIZE_CHANNEL_ENTRIES
+ + DUAL_GEOMETRY_ENTRIES
+)
diff --git a/backend/app/nodes/annotations.py b/backend/app/nodes/annotations.py
new file mode 100644
index 0000000..1c808c3
--- /dev/null
+++ b/backend/app/nodes/annotations.py
@@ -0,0 +1,112 @@
+"""Starter node that emits bbox / keypoint annotation payloads."""
+
+from __future__ import annotations
+
+import json
+from typing import Any
+
+from app.engine.registry import BaseNode
+from app.nodes.common import bboxes_out, keypoints_out, string_param
+
+
+def _parse_json_list(raw: Any, *, label: str) -> list[Any]:
+ if raw is None or raw == "":
+ return []
+ if isinstance(raw, list):
+ return raw
+ if not isinstance(raw, str):
+ raise ValueError(f"{label} must be a JSON array string")
+ try:
+ parsed = json.loads(raw)
+ except json.JSONDecodeError as exc:
+ raise ValueError(f"Invalid JSON for {label}: {exc}") from exc
+ if not isinstance(parsed, list):
+ raise ValueError(f"{label} JSON must be an array")
+ return parsed
+
+
+def _validate_bboxes(items: list[Any]) -> list[list[Any]]:
+ result: list[list[Any]] = []
+ for item in items:
+ if not isinstance(item, (list, tuple)) or len(item) < 4:
+ raise ValueError(
+ "Each bbox must be [x_min, y_min, x_max, y_max, label?] (Pascal VOC)"
+ )
+ box = [
+ float(item[0]),
+ float(item[1]),
+ float(item[2]),
+ float(item[3]),
+ str(item[4]) if len(item) >= 5 else "object",
+ ]
+ if box[2] <= box[0] or box[3] <= box[1]:
+ raise ValueError(f"Invalid bbox extents: {box[:4]}")
+ result.append(box)
+ return result
+
+
+def _validate_keypoints(items: list[Any]) -> list[list[float]]:
+ result: list[list[float]] = []
+ for item in items:
+ if not isinstance(item, (list, tuple)) or len(item) < 2:
+ raise ValueError("Each keypoint must be [x, y]")
+ result.append([float(item[0]), float(item[1])])
+ return result
+
+
+class AnnotationsNode(BaseNode):
+ type = "annotations"
+ label = "Annotations"
+ category = "starters"
+ description = (
+ "Emit Pascal-VOC bboxes and xy keypoints for Albumentations dual ports."
+ )
+ ports = [bboxes_out(), keypoints_out()]
+ params = [
+ string_param(
+ "bboxes_json",
+ "BBoxes JSON",
+ '[[10, 10, 100, 80, "object"]]',
+ description='Pascal VOC array: [[x_min, y_min, x_max, y_max, label], ...]',
+ ),
+ string_param(
+ "keypoints_json",
+ "Keypoints JSON",
+ "[[40, 40], [80, 60]]",
+ description="XY keypoints array: [[x, y], ...]",
+ ),
+ ]
+ cacheable = True
+ stochastic = False
+
+ def execute(
+ self,
+ inputs: dict[str, Any],
+ params: dict[str, Any],
+ seed: int = 0,
+ ) -> dict[str, Any]:
+ del inputs, seed
+ bboxes = _validate_bboxes(_parse_json_list(params.get("bboxes_json"), label="bboxes"))
+ keypoints = _validate_keypoints(
+ _parse_json_list(params.get("keypoints_json"), label="keypoints")
+ )
+ return {"bboxes": bboxes, "keypoints": keypoints}
+
+ def emit_python(
+ self,
+ node_id: str,
+ params: dict[str, Any],
+ input_vars: dict[str, str],
+ output_vars: dict[str, str],
+ ) -> list[str]:
+ del node_id, input_vars
+ bboxes = _validate_bboxes(_parse_json_list(params.get("bboxes_json"), label="bboxes"))
+ keypoints = _validate_keypoints(
+ _parse_json_list(params.get("keypoints_json"), label="keypoints")
+ )
+ lines: list[str] = []
+ if "bboxes" in output_vars:
+ lines.append(f"{output_vars['bboxes']} = {bboxes!r}")
+ if "keypoints" in output_vars:
+ lines.append(f"{output_vars['keypoints']} = {keypoints!r}")
+ return lines or ["pass"]
diff --git a/backend/tests/test_albumentations.py b/backend/tests/test_albumentations.py
new file mode 100644
index 0000000..b7c52f3
--- /dev/null
+++ b/backend/tests/test_albumentations.py
@@ -0,0 +1,192 @@
+"""Tests for Albumentations multi-target augment nodes."""
+
+from __future__ import annotations
+
+import numpy as np
+
+from app.engine.cache import CacheManager
+from app.engine.executor import DagExecutor
+from app.engine.registry import registry
+from app.models.graph import Edge, ExecuteRequest, Graph, NodeInstance
+from app.nodes import register_builtin_nodes
+
+
+def _image() -> np.ndarray:
+ image = np.full((64, 64, 3), 90, dtype=np.uint8)
+ image[8:40, 8:40] = (30, 180, 70)
+ return image
+
+
+def test_augment_nodes_registered() -> None:
+ register_builtin_nodes()
+ augment = [meta for meta in registry.list_metadata() if meta.category == "augment"]
+ assert len(augment) >= 50
+ assert registry.has("albu_horizontal_flip")
+ assert registry.has("albu_random_brightness_contrast")
+ assert registry.has("annotations")
+
+
+def test_image_only_passthrough_annotations() -> None:
+ register_builtin_nodes()
+ node = registry.get("albu_random_brightness_contrast")
+ params = node.validate_params({"p": 1.0, "brightness_limit": 0.1, "contrast_limit": 0.1})
+ bboxes = [[8, 8, 40, 40, "car"]]
+ keypoints = [[20.0, 20.0]]
+ mask = np.zeros((64, 64), dtype=np.uint8)
+ mask[8:40, 8:40] = 255
+ out = node.execute(
+ {"image": _image(), "mask": mask, "bboxes": bboxes, "keypoints": keypoints},
+ params,
+ seed=3,
+ )
+ assert out["image"].shape == (64, 64, 3)
+ assert out["bboxes"] == bboxes
+ assert out["keypoints"] == keypoints
+ assert out["mask"].shape[:2] == (64, 64)
+
+
+def test_dual_flip_updates_bboxes_and_keypoints() -> None:
+ register_builtin_nodes()
+ node = registry.get("albu_horizontal_flip")
+ params = node.validate_params({"p": 1.0})
+ out = node.execute(
+ {
+ "image": _image(),
+ "bboxes": [[8, 8, 40, 40, "car"]],
+ "keypoints": [[20.0, 12.0]],
+ },
+ params,
+ seed=0,
+ )
+ # x mirrored in 64-wide image: x' = W - x
+ assert out["bboxes"][0][0] == 24.0
+ assert out["bboxes"][0][2] == 56.0
+ assert out["bboxes"][0][4] == "car"
+ assert out["keypoints"][0][0] == 43.0
+ assert out["keypoints"][0][1] == 12.0
+
+
+def test_seed_reproducibility() -> None:
+ register_builtin_nodes()
+ node = registry.get("albu_gauss_noise")
+ params = node.validate_params({"p": 1.0})
+ a = node.execute({"image": _image()}, params, seed=11)["image"]
+ b = node.execute({"image": _image()}, params, seed=11)["image"]
+ c = node.execute({"image": _image()}, params, seed=12)["image"]
+ assert np.array_equal(a, b)
+ assert not np.array_equal(a, c)
+
+
+def test_optional_ports_omitted() -> None:
+ register_builtin_nodes()
+ node = registry.get("albu_gaussian_blur")
+ params = node.validate_params({"p": 1.0, "blur_limit": 5})
+ out = node.execute({"image": _image()}, params, seed=0)
+ assert set(out.keys()) == {"image"}
+
+
+def test_annotations_node_and_pipeline(tmp_path) -> None:
+ register_builtin_nodes()
+ ann = registry.get("annotations")
+ payload = ann.execute(
+ {},
+ ann.validate_params(
+ {
+ "bboxes_json": '[[5, 5, 30, 30, "a"]]',
+ "keypoints_json": "[[10, 12]]",
+ }
+ ),
+ seed=0,
+ )
+ assert payload["bboxes"][0][4] == "a"
+ assert payload["keypoints"] == [[10.0, 12.0]]
+
+ # Cache mixed ports from a dual node.
+ flip = registry.get("albu_horizontal_flip")
+ produced = flip.execute(
+ {"image": _image(), "bboxes": payload["bboxes"], "keypoints": payload["keypoints"]},
+ flip.validate_params({"p": 1.0}),
+ seed=0,
+ )
+ cache = CacheManager(tmp_path / "cache")
+ key = cache.make_key(
+ "albu_horizontal_flip",
+ {"p": 1.0},
+ {port: cache.hash_value(value) for port, value in produced.items()},
+ seed=0,
+ )
+ cache.put_outputs(key, produced)
+ loaded = cache.get_outputs(key)
+ assert loaded is not None
+ assert loaded["bboxes"] == produced["bboxes"]
+ assert np.array_equal(loaded["image"], produced["image"])
+
+
+def test_executor_runs_annotations_to_flip(tmp_path) -> None:
+ register_builtin_nodes()
+ image_path = tmp_path / "in.png"
+ import cv2
+
+ cv2.imwrite(str(image_path), _image())
+ request = ExecuteRequest(
+ graph=Graph(
+ nodes=[
+ NodeInstance(
+ id="load",
+ type="load_image",
+ params={"path": str(image_path)},
+ ),
+ NodeInstance(
+ id="ann",
+ type="annotations",
+ params={
+ "bboxes_json": "[[8, 8, 40, 40, \"car\"]]",
+ "keypoints_json": "[[20, 20]]",
+ },
+ ),
+ NodeInstance(id="flip", type="albu_horizontal_flip", params={"p": 1.0}),
+ ],
+ edges=[
+ Edge(
+ id="e1",
+ source="load",
+ source_port="image",
+ target="flip",
+ target_port="image",
+ ),
+ Edge(
+ id="e2",
+ source="ann",
+ source_port="bboxes",
+ target="flip",
+ target_port="bboxes",
+ ),
+ Edge(
+ id="e3",
+ source="ann",
+ source_port="keypoints",
+ target="flip",
+ target_port="keypoints",
+ ),
+ ],
+ ),
+ seed=0,
+ cache=True,
+ )
+ events: list[dict] = []
+ executor = DagExecutor(tmp_path / "cache", node_registry=registry)
+ result = executor.execute(
+ request,
+ on_event=lambda event: events.append(event.model_dump())
+ if event.type.value == "preview"
+ else None,
+ )
+ assert "flip" in result["order"]
+ flip_previews = [
+ event
+ for event in events
+ if event.get("node_id") == "flip" and event.get("port_id") == "image"
+ ]
+ assert flip_previews
+ assert flip_previews[0].get("data") is not None
+ assert "bboxes" in flip_previews[0]["data"]