Skip to content

port RandomHorizontalFlip to prototype API #5563

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 56 additions & 2 deletions test/test_prototype_transforms.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@

import pytest
import torch
from common_utils import assert_equal
from test_prototype_transforms_functional import make_images, make_bounding_boxes, make_one_hot_labels
from torchvision.prototype import transforms, features
from torchvision.transforms.functional import to_pil_image
from torchvision.transforms.functional import to_pil_image, pil_to_tensor


def make_vanilla_tensor_images(*args, **kwargs):
Expand Down Expand Up @@ -66,10 +67,10 @@ def parametrize_from_transforms(*transforms):
class TestSmoke:
@parametrize_from_transforms(
transforms.RandomErasing(p=1.0),
transforms.HorizontalFlip(),
transforms.Resize([16, 16]),
transforms.CenterCrop([16, 16]),
transforms.ConvertImageDtype(),
transforms.RandomHorizontalFlip(),
)
def test_common(self, transform, input):
transform(input)
Expand Down Expand Up @@ -152,3 +153,56 @@ def test_normalize(self, transform, input):
)
def test_random_resized_crop(self, transform, input):
transform(input)


class TestRandomHorizontalFlip:
def input_tensor(self, dtype: torch.dtype = torch.float32) -> torch.Tensor:
return torch.tensor([[[0, 1], [0, 1]], [[1, 0], [1, 0]]], dtype=dtype)

def expected_tensor(self, dtype: torch.dtype = torch.float32) -> torch.Tensor:
return torch.tensor([[[1, 0], [1, 0]], [[0, 1], [0, 1]]], dtype=dtype)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure we need specific values here. I think we should be good to have random image inputs and use torch.flip. I'm aware that this is the only call in the kernel

def hflip(img: Tensor) -> Tensor:
_assert_image_tensor(img)
return img.flip(-1)

but this is also what I would use to produce a expected output if I didn't know the internals of the kernel. cc @NicolasHug for an opinion

Copy link
Contributor Author

@federicopozzi33 federicopozzi33 Mar 10, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I used specific values to have full control over the creation of the expecting result. I preferred to not use the torch.flip to not "mock" the internals of the transformation.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

cc @NicolasHug for an opinion

No strong opinion on my side for this specific transform. In some cases it's valuable to have a simple implementation of the transform that we're testing - it helps understanding what's going on with simpler code, and we can call it on arbitrary input. In the case of flip the transform is very elementary and doesn't need much explaining anyway.

If we're confident that this hard-coded input covers all of what we might want to test against, then that's fine.


@pytest.mark.parametrize("p", [0.0, 1.0], ids=["p=0", "p=1"])
def test_simple_tensor(self, p: float):
input = self.input_tensor()

actual = transforms.RandomHorizontalFlip(p=p)(input)

expected = self.expected_tensor() if p == 1.0 else input
assert_equal(expected, actual)

@pytest.mark.parametrize("p", [0.0, 1.0], ids=["p=0", "p=1"])
def test_pil_image(self, p: float):
input = self.input_tensor(dtype=torch.uint8)

actual = transforms.RandomHorizontalFlip(p=p)(to_pil_image(input))

expected = self.expected_tensor(dtype=torch.uint8) if p == 1.0 else input
assert_equal(expected, pil_to_tensor(actual))

@pytest.mark.parametrize("p", [0.0, 1.0], ids=["p=0", "p=1"])
def test_features_image(self, p: float):
input = self.input_tensor()

actual = transforms.RandomHorizontalFlip(p=p)(features.Image(input))

expected = self.expected_tensor() if p == 1.0 else input
assert_equal(features.Image(expected), actual)

@pytest.mark.parametrize("p", [0.0, 1.0], ids=["p=0", "p=1"])
def test_features_segmentation_mask(self, p: float):
input = features.SegmentationMask(self.input_tensor())

actual = transforms.RandomHorizontalFlip(p=p)(input)

expected = self.expected_tensor() if p == 1.0 else input
assert_equal(features.SegmentationMask(expected), actual)

@pytest.mark.parametrize("p", [0.0, 1.0], ids=["p=0", "p=1"])
def test_features_bounding_box(self, p: float):
input = features.BoundingBox([0, 0, 5, 5], format=features.BoundingBoxFormat.XYXY, image_size=(10, 10))

actual = transforms.RandomHorizontalFlip(p=p)(input)

expected = torch.tensor([5, 0, 10, 5]) if p == 1.0 else input
assert_equal(features.BoundingBox.new_like(input, expected), actual)
10 changes: 9 additions & 1 deletion torchvision/prototype/transforms/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,15 @@
from ._augment import RandomErasing, RandomMixup, RandomCutmix
from ._auto_augment import RandAugment, TrivialAugmentWide, AutoAugment, AugMix
from ._container import Compose, RandomApply, RandomChoice, RandomOrder
from ._geometry import HorizontalFlip, Resize, CenterCrop, RandomResizedCrop, FiveCrop, TenCrop, BatchMultiCrop
from ._geometry import (
Resize,
CenterCrop,
RandomResizedCrop,
FiveCrop,
TenCrop,
BatchMultiCrop,
RandomHorizontalFlip,
)
from ._meta import ConvertBoundingBoxFormat, ConvertImageDtype, ConvertImageColorSpace
from ._misc import Identity, Normalize, ToDtype, Lambda
from ._presets import (
Expand Down
16 changes: 15 additions & 1 deletion torchvision/prototype/transforms/_geometry.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,25 @@
from ._utils import query_image, get_image_dimensions, has_any, is_simple_tensor


class HorizontalFlip(Transform):
class RandomHorizontalFlip(Transform):
def __init__(self, p: float = 0.5) -> None:
super().__init__()
self.p = p

def forward(self, *inputs: Any) -> Any:
sample = inputs if len(inputs) > 1 else inputs[0]
if torch.rand(1) >= self.p:
return sample

return super().forward(sample)

def _transform(self, input: Any, params: Dict[str, Any]) -> Any:
if isinstance(input, features.Image):
output = F.horizontal_flip_image_tensor(input)
return features.Image.new_like(input, output)
elif isinstance(input, features.SegmentationMask):
output = F.horizontal_flip_segmentation_mask(input)
return features.SegmentationMask.new_like(input, output)
elif isinstance(input, features.BoundingBox):
output = F.horizontal_flip_bounding_box(input, format=input.format, image_size=input.image_size)
return features.BoundingBox.new_like(input, output)
Expand Down
1 change: 1 addition & 0 deletions torchvision/prototype/transforms/functional/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@
horizontal_flip_bounding_box,
horizontal_flip_image_tensor,
horizontal_flip_image_pil,
horizontal_flip_segmentation_mask,
resize_bounding_box,
resize_image_tensor,
resize_image_pil,
Expand Down
4 changes: 4 additions & 0 deletions torchvision/prototype/transforms/functional/_geometry.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@
horizontal_flip_image_pil = _FP.hflip


def horizontal_flip_segmentation_mask(segmentation_mask: torch.Tensor) -> torch.Tensor:
return horizontal_flip_image_tensor(segmentation_mask)


def horizontal_flip_bounding_box(
bounding_box: torch.Tensor, format: features.BoundingBoxFormat, image_size: Tuple[int, int]
) -> torch.Tensor:
Expand Down