Skip to content

cofai.transforms

Project-level transform recipes and builders.

This package is the preferred place to define composable evaluation/training transform pipelines (YAML-friendly dicts + small Python helpers).

Dataset-specific adapters may still live under cofai.datasets, but reusable transform composition should be imported from here.

AddIgnoreRegions

AddIgnoreRegions(keys: Optional[Sequence[str]] = None)

Add Ignore Regions

CenterCropImage

CenterCropImage(size: Any, keys: Optional[Sequence[str]] = None)

Thin adapter over torchvision.transforms.v2.CenterCrop.

Applies a center crop of the given size to each sample[key]. Sample entries must be HWC numpy arrays.

MLoRETransformsConfig dataclass

MLoRETransformsConfig(train_scale: Tuple[int, int] = (512, 512), test_scale: Tuple[int, int] = (512, 512), enable_random_scaling: bool = True, random_scaling_factors: Tuple[float, float] = (0.5, 2.0), random_scaling_discrete: bool = False, enable_random_crop: bool = True, random_crop_cat_max_ratio: float = 0.75, enable_hflip: bool = True, hflip_p: float = 0.5, enable_photometric: bool = True, mean: Tuple[float, float, float] = (0.485, 0.456, 0.406), std: Tuple[float, float, float] = (0.229, 0.224, 0.225))

Configurable transform recipe for RFC/MLoRE datasets.

This is intentionally lightweight: it only controls which building blocks are included and their key parameters. The underlying blocks live in cofai.transforms (preferred YAML namespace; implementation in cofai.transforms.core).

Normalize

Normalize(mean, std, keys: Optional[Sequence[str]] = None)

Normalize image values by first mapping from [0, 255] to [0, 1] and then applying standardization.

PadImage

PadImage(size, keys: Optional[Sequence[str]] = None)

Pad image and label to have dimensions >= [size_height, size_width] Args: size: Desired size Returns: sample: The input sample padded

PadToMultiple

PadToMultiple(multiple: int, keys: Optional[Sequence[str]] = None)

Center-pad so H and W become multiples of multiple (see fill_index per key).

If keys is set, only those sample keys are padded (must exist). Otherwise only img is padded.

PhotoMetricDistortion

PhotoMetricDistortion(brightness_delta=32, contrast_range=(0.5, 1.5), saturation_range=(0.5, 1.5), hue_delta=18, keys: Optional[Sequence[str]] = None)

Apply photometric distortion to image sequentially, every transformation is applied with a probability of 0.5. The position of random contrast is in second or second to last. 1. random brightness 2. random contrast (mode 0) 3. convert color from BGR to HSV 4. random saturation 5. random hue 6. convert color from HSV to BGR 7. random contrast (mode 1) 8. randomly swap channels Args: brightness_delta (int): delta of brightness. contrast_range (tuple): range of contrast. saturation_range (tuple): range of saturation. hue_delta (int): delta of hue.

brightness

brightness(img)

Brightness distortion.

contrast

contrast(img)

Contrast distortion.

convert

convert(img, alpha=1, beta=0)

Multiple with alpha and add beat with clip.

hue

hue(img)

Hue distortion.

saturation

saturation(img)

Saturation distortion.

RandomCrop

RandomCrop(size, cat_max_ratio=1, keys: Optional[Sequence[str]] = None)

Random crop image if it exceeds desired size Args: size: Desired size Returns: sample: The input sample randomly cropped

get_random_crop_loc

get_random_crop_loc(uncropped)

Gets a random crop location. Args: key: Key indicating the uncropped input origin uncropped: Image or target to be cropped. Returns: Cropping region.

RandomHorizontalFlip

RandomHorizontalFlip(p=0.5, keys: Optional[Sequence[str]] = None)

Horizontally flip the given image and ground truth randomly.

RandomScaling

RandomScaling(scale_factors=(0.5, 2.0), discrete=False, keys: Optional[Sequence[str]] = None)

Random scale the input. Args: min_scale_factor: Minimum scale value. max_scale_factor: Maximum scale value. step_size: The step size from minimum to maximum value. Returns: sample: The input sample scaled

scale

scale(key, unscaled, scale=1.0)

Randomly scales image and label. Args: key: Key indicating the uscaled input origin unscaled: Image or target to be scaled. scale: The value to scale image and label. Returns: scaled: The scaled image or target

ResizeImage

ResizeImage(size: Any, keys: Optional[Sequence[str]] = None, *, interpolation: Any = InterpolationMode.BILINEAR, max_size: Optional[int] = None, antialias: Optional[bool] = True)

Thin adapter over torchvision.transforms.v2.Resize.

Constructor arguments match TorchVision (size, interpolation, max_size, antialias). The only CoFAI extra is keys: the same resize is applied to each sample[key].

Sample entries must be HWC numpy arrays (use float32 for images). TorchVision operates on CHW tensors, so this class only converts layout and dtype; all scaling rules and errors come from TvResize.

ResizeToFit

ResizeToFit(size, keys: Optional[Sequence[str]] = None)

Resize image/targets to fit within a max canvas size.

  • Preserves aspect ratio.
  • Only resizes when input is larger than size in either dimension.
  • Uses bilinear for image and nearest for discrete targets.

SetImageAsOriginal

Set meta["ori_size"] to current img spatial size (H, W).

ToTensor

ToTensor(keys: Optional[Sequence[str]] = None)

Convert ndarrays in sample to Tensors.

get_mlore_train_transforms

get_mlore_train_transforms(p: Any = None, cfg: Optional[MLoRETransformsConfig] = None)

Return the RFC/MLoRE training transform pipeline (augment + pad + tensor).

get_mlore_transforms

get_mlore_transforms(p: Any = None, split: str = 'train', cfg: Optional[MLoRETransformsConfig] = None)

Get data transforms for MLoRE datasets.

Backward compatible API: - Old callers: get_mlore_transforms(p, split) keep working. - New callers: pass cfg=MLoRETransformsConfig(...) to configure behavior.

Notes: - For split != "train" (val/test), this pipeline does not resize; it pads image + labels to cfg.test_scale and uses ignore regions for padded areas.

get_mlore_transforms_cfg

get_mlore_transforms_cfg(p: Any = None, split: str = 'train', cfg: Optional[MLoRETransformsConfig] = None) -> Dict[str, Any]

Return a config dict (YAML-friendly) describing the RFC/MLoRE transform pipeline.

This enables composing fine-grained blocks (Normalize/PadImage/ToTensor/...) via config files. The returned dict follows this project's convention:

  • type: torchvision.transforms.Compose
  • transforms: [{type: , ...}, ...]

Notes: - For val/test, this pipeline does not resize; it pads to test_scale and uses ignore labels. - For train, resize-like behavior comes from RandomScaling (data augmentation).

get_mlore_val_transforms

get_mlore_val_transforms(p: Any = None, cfg: Optional[MLoRETransformsConfig] = None)

Return the RFC/MLoRE validation/test transform pipeline (normalize + pad + tensor).