from typing import Dict, List, Optional, Tuple import torch import torch.nn.functional as F from torch import Tensor from torchvision import transforms from torchvision.transforms import InterpolationMode from torchvision.transforms import functional as F from torchvision.transforms.autoaugment import _apply_op class STNAugment(torch.nn.Module): r"""RandAugment data augmentation method based on `"RandAugment: Practical automated data augmentation with a reduced search space" `_. If the image is torch Tensor, it should be of type torch.uint8, and it is expected to have [..., 1 or 3, H, W] shape, where ... means an arbitrary number of leading dimensions. If img is PIL Image, it is expected to be in mode "L" or "RGB". Args: num_ops (int): Number of augmentation transformations to apply sequentially. magnitude (int): Magnitude for all the transformations. num_magnitude_bins (int): The number of different magnitude values. interpolation (InterpolationMode): Desired interpolation enum defined by :class:`torchvision.transforms.InterpolationMode`. Default is ``InterpolationMode.NEAREST``. If input is Tensor, only ``InterpolationMode.NEAREST``, ``InterpolationMode.BILINEAR`` are supported. fill (sequence or number, optional): Pixel fill value for the area outside the transformed image. If given a number, the value is used for all bands respectively. """ def __init__( self, num_ops: int = 2, magnitude: int = 9, num_magnitude_bins: int = 31, interpolation: InterpolationMode = InterpolationMode.NEAREST, fill: Optional[List[float]] = None, ) -> None: super().__init__() self.num_ops = num_ops self.magnitude = magnitude self.num_magnitude_bins = num_magnitude_bins self.interpolation = interpolation self.fill = fill self.aug = transforms.Compose([ transforms.RandomVerticalFlip(0.2), ]) def _augmentation_space(self, num_bins: int, image_size: Tuple[int, int]) -> Dict[str, Tuple[Tensor, bool]]: return { # op_name: (magnitudes, signed) "Identity": (torch.tensor(0.0), False), "ShearX": (torch.linspace(0.0, 0.3, num_bins), True), "ShearY": (torch.linspace(0.0, 0.3, num_bins), True), "TranslateX": (torch.linspace(0.0, 150.0 / 331.0 * image_size[1], num_bins), True), "TranslateY": (torch.linspace(0.0, 150.0 / 331.0 * image_size[0], num_bins), True), "Rotate": (torch.linspace(0.0, 30.0, num_bins), True), } def forward(self, img: List[Tensor]): """ img (PIL Image or Tensor): Image to be transformed. Returns: PIL Image or Tensor: Transformed image. """ fill = self.fill cat_img= torch.cat(img) imgs = list(torch.chunk(cat_img,cat_img.shape[0],0)) channels, height, width = imgs[0].shape if isinstance(imgs[0], Tensor): if isinstance(fill, (int, float)): fill = [float(fill)] * channels elif fill is not None: fill = [float(f) for f in fill] op_meta = self._augmentation_space(self.num_magnitude_bins, (height, width)) for _ in range(self.num_ops): op_index = int(torch.randint(len(op_meta), (1,)).item()) op_name = list(op_meta.keys())[op_index] magnitudes, signed = op_meta[op_name] magnitude = float(magnitudes[self.magnitude].item()) if magnitudes.ndim > 0 else 0.0 if signed and torch.randint(2, (1,)): magnitude *= -1.0 for i in range(len(imgs)): imgs[i] = _apply_op(imgs[i], op_name, magnitude, interpolation=self.interpolation, fill=fill) return imgs def __repr__(self) -> str: s = ( f"{self.__class__.__name__}(" f"num_ops={self.num_ops}" f", magnitude={self.magnitude}" f", num_magnitude_bins={self.num_magnitude_bins}" f", interpolation={self.interpolation}" f", fill={self.fill}" f")" ) return s