diff --git a/test/test_transforms_v2.py b/test/test_transforms_v2.py index b9f440bd545..29839dcf9e4 100644 --- a/test/test_transforms_v2.py +++ b/test/test_transforms_v2.py @@ -21,6 +21,7 @@ import torchvision.transforms.v2 as transforms from common_utils import ( + assert_close, assert_equal, cache, cpu_and_cuda, @@ -42,7 +43,6 @@ ) from torch import nn -from torch.testing import assert_close from torch.utils._pytree import tree_flatten, tree_map from torch.utils.data import DataLoader, default_collate from torchvision import tv_tensors @@ -5172,6 +5172,7 @@ def test_kernel_video(self): make_segmentation_mask, make_video, make_keypoints, + pytest.param(make_image_cvcuda, marks=pytest.mark.needs_cvcuda), ], ) def test_functional(self, make_input): @@ -5187,9 +5188,16 @@ def test_functional(self, make_input): (F.perspective_mask, tv_tensors.Mask), (F.perspective_video, tv_tensors.Video), (F.perspective_keypoints, tv_tensors.KeyPoints), + pytest.param( + F._geometry._perspective_image_cvcuda, + None, + marks=pytest.mark.needs_cvcuda, + ), ], ) def test_functional_signature(self, kernel, input_type): + if kernel is F._geometry._perspective_image_cvcuda: + input_type = _import_cvcuda().Tensor check_functional_kernel_signature_match(F.perspective, kernel=kernel, input_type=input_type) @pytest.mark.parametrize("distortion_scale", [0.5, 0.0, 1.0]) @@ -5203,6 +5211,7 @@ def test_functional_signature(self, kernel, input_type): make_segmentation_mask, make_video, make_keypoints, + pytest.param(make_image_cvcuda, marks=pytest.mark.needs_cvcuda), ], ) def test_transform(self, distortion_scale, make_input): @@ -5218,12 +5227,23 @@ def test_transform_error(self, distortion_scale): "interpolation", [transforms.InterpolationMode.NEAREST, transforms.InterpolationMode.BILINEAR] ) @pytest.mark.parametrize("fill", CORRECTNESS_FILLS) - def test_image_functional_correctness(self, coefficients, interpolation, fill): - image = make_image(dtype=torch.uint8, device="cpu") + @pytest.mark.parametrize( + "make_input", + [ + make_image, + pytest.param(make_image_cvcuda, marks=pytest.mark.needs_cvcuda), + ], + ) + def test_image_functional_correctness(self, coefficients, interpolation, fill, make_input): + image = make_input(dtype=torch.uint8, device="cpu") actual = F.perspective( image, startpoints=None, endpoints=None, coefficients=coefficients, interpolation=interpolation, fill=fill ) + if make_input is make_image_cvcuda: + actual = F.cvcuda_to_tensor(actual)[0].cpu() + image = F.cvcuda_to_tensor(image)[0].cpu() + expected = F.to_image( F.perspective( F.to_pil_image(image), @@ -5235,13 +5255,20 @@ def test_image_functional_correctness(self, coefficients, interpolation, fill): ) ) - if interpolation is transforms.InterpolationMode.BILINEAR: - abs_diff = (actual.float() - expected.float()).abs() - assert (abs_diff > 1).float().mean() < 7e-2 - mae = abs_diff.mean() - assert mae < 3 - else: - assert_equal(actual, expected) + if make_input is make_image: + if interpolation is transforms.InterpolationMode.BILINEAR: + abs_diff = (actual.float() - expected.float()).abs() + assert (abs_diff > 1).float().mean() < 7e-2 + mae = abs_diff.mean() + assert mae < 3 + else: + assert_equal(actual, expected) + else: # CV-CUDA + # just check that the shapes/dtypes are the same, cvcuda warp_perspective uses different algorithm + # visually the results are the same on real images, + # realistically, the diff is not visible to the human eye + tolerance = 255 if interpolation is transforms.InterpolationMode.NEAREST else 125 + assert_close(actual, expected, rtol=0, atol=tolerance) def _reference_perspective_bounding_boxes(self, bounding_boxes, *, startpoints, endpoints): format = bounding_boxes.format diff --git a/torchvision/transforms/v2/_geometry.py b/torchvision/transforms/v2/_geometry.py index 96166e05e9a..f2d7675e0be 100644 --- a/torchvision/transforms/v2/_geometry.py +++ b/torchvision/transforms/v2/_geometry.py @@ -944,6 +944,8 @@ class RandomPerspective(_RandomApplyTransform): _v1_transform_cls = _transforms.RandomPerspective + _transformed_types = _RandomApplyTransform._transformed_types + (_is_cvcuda_tensor,) + def __init__( self, distortion_scale: float = 0.5, diff --git a/torchvision/transforms/v2/_utils.py b/torchvision/transforms/v2/_utils.py index bb6051b4e61..e803aa49c60 100644 --- a/torchvision/transforms/v2/_utils.py +++ b/torchvision/transforms/v2/_utils.py @@ -16,7 +16,7 @@ from torchvision.transforms.transforms import _check_sequence_input, _setup_angle, _setup_size # noqa: F401 from torchvision.transforms.v2.functional import get_dimensions, get_size, is_pure_tensor -from torchvision.transforms.v2.functional._utils import _FillType, _FillTypeJIT +from torchvision.transforms.v2.functional._utils import _FillType, _FillTypeJIT, _is_cvcuda_tensor def _setup_number_or_seq(arg: int | float | Sequence[int | float], name: str) -> Sequence[float]: @@ -182,7 +182,7 @@ def query_chw(flat_inputs: list[Any]) -> tuple[int, int, int]: chws = { tuple(get_dimensions(inpt)) for inpt in flat_inputs - if check_type(inpt, (is_pure_tensor, tv_tensors.Image, PIL.Image.Image, tv_tensors.Video)) + if check_type(inpt, (is_pure_tensor, tv_tensors.Image, PIL.Image.Image, tv_tensors.Video, _is_cvcuda_tensor)) } if not chws: raise TypeError("No image or video was found in the sample") @@ -207,6 +207,7 @@ def query_size(flat_inputs: list[Any]) -> tuple[int, int]: tv_tensors.Mask, tv_tensors.BoundingBoxes, tv_tensors.KeyPoints, + _is_cvcuda_tensor, ), ) } diff --git a/torchvision/transforms/v2/functional/_geometry.py b/torchvision/transforms/v2/functional/_geometry.py index 0e27218bc89..0ad384ceffa 100644 --- a/torchvision/transforms/v2/functional/_geometry.py +++ b/torchvision/transforms/v2/functional/_geometry.py @@ -4,6 +4,7 @@ from collections.abc import Sequence from typing import Any, Optional, TYPE_CHECKING, Union +import numpy as np import PIL.Image import torch from torch.nn.functional import grid_sample, interpolate, pad as torch_pad @@ -28,6 +29,7 @@ from ._utils import ( _FillTypeJIT, + _get_cvcuda_interp, _get_kernel, _import_cvcuda, _is_cvcuda_available, @@ -2285,6 +2287,44 @@ def perspective_video( ) +def _perspective_image_cvcuda( + image: "cvcuda.Tensor", + startpoints: Optional[list[list[int]]], + endpoints: Optional[list[list[int]]], + interpolation: Union[InterpolationMode, int] = InterpolationMode.BILINEAR, + fill: _FillTypeJIT = None, + coefficients: Optional[list[float]] = None, +) -> "cvcuda.Tensor": + cvcuda = _import_cvcuda() + + c = _perspective_coefficients(startpoints, endpoints, coefficients) + interpolation = _check_interpolation(interpolation) + + interp = _get_cvcuda_interp(interpolation) + + xform = np.array([[c[0], c[1], c[2]], [c[3], c[4], c[5]], [c[6], c[7], 1.0]], dtype=np.float32) + + num_channels = image.shape[-1] + if fill is None: + border_value = np.zeros(num_channels, dtype=np.float32) + elif isinstance(fill, (int, float)): + border_value = np.full(num_channels, fill, dtype=np.float32) + else: + border_value = np.array(fill, dtype=np.float32)[:num_channels] + + return cvcuda.warp_perspective( + image, + xform, + flags=interp | cvcuda.Interp.WARP_INVERSE_MAP, + border_mode=cvcuda.Border.CONSTANT, + border_value=border_value, + ) + + +if CVCUDA_AVAILABLE: + _register_kernel_internal(perspective, _import_cvcuda().Tensor)(_perspective_image_cvcuda) + + def elastic( inpt: torch.Tensor, displacement: torch.Tensor, diff --git a/torchvision/transforms/v2/functional/_utils.py b/torchvision/transforms/v2/functional/_utils.py index 11480b30ef9..4ad08006b00 100644 --- a/torchvision/transforms/v2/functional/_utils.py +++ b/torchvision/transforms/v2/functional/_utils.py @@ -1,9 +1,13 @@ import functools from collections.abc import Sequence -from typing import Any, Callable, Optional, Union +from typing import Any, Callable, Optional, TYPE_CHECKING, Union import torch from torchvision import tv_tensors +from torchvision.transforms.functional import InterpolationMode + +if TYPE_CHECKING: + import cvcuda # type: ignore[import-not-found] _FillType = Union[int, float, Sequence[int], Sequence[float], None] _FillTypeJIT = Optional[list[float]] @@ -177,3 +181,37 @@ def _is_cvcuda_tensor(inpt: Any) -> bool: return isinstance(inpt, cvcuda.Tensor) except ImportError: return False + + +_interpolation_mode_to_cvcuda_interp: dict[InterpolationMode | str | int, "cvcuda.Interp"] = {} + + +def _get_cvcuda_interp(interpolation: InterpolationMode | str | int) -> "cvcuda.Interp": + if not _interpolation_mode_to_cvcuda_interp: + cvcuda = _import_cvcuda() + _interpolation_mode_to_cvcuda_interp[InterpolationMode.NEAREST] = cvcuda.Interp.NEAREST + _interpolation_mode_to_cvcuda_interp[InterpolationMode.NEAREST_EXACT] = cvcuda.Interp.NEAREST + _interpolation_mode_to_cvcuda_interp[InterpolationMode.BILINEAR] = cvcuda.Interp.LINEAR + _interpolation_mode_to_cvcuda_interp[InterpolationMode.BICUBIC] = cvcuda.Interp.CUBIC + _interpolation_mode_to_cvcuda_interp[InterpolationMode.BOX] = cvcuda.Interp.BOX + _interpolation_mode_to_cvcuda_interp[InterpolationMode.HAMMING] = cvcuda.Interp.HAMMING + _interpolation_mode_to_cvcuda_interp[InterpolationMode.LANCZOS] = cvcuda.Interp.LANCZOS + _interpolation_mode_to_cvcuda_interp["nearest"] = cvcuda.Interp.NEAREST + _interpolation_mode_to_cvcuda_interp["nearest-exact"] = cvcuda.Interp.NEAREST + _interpolation_mode_to_cvcuda_interp["bilinear"] = cvcuda.Interp.LINEAR + _interpolation_mode_to_cvcuda_interp["bicubic"] = cvcuda.Interp.CUBIC + _interpolation_mode_to_cvcuda_interp["box"] = cvcuda.Interp.BOX + _interpolation_mode_to_cvcuda_interp["hamming"] = cvcuda.Interp.HAMMING + _interpolation_mode_to_cvcuda_interp["lanczos"] = cvcuda.Interp.LANCZOS + _interpolation_mode_to_cvcuda_interp[0] = cvcuda.Interp.NEAREST + _interpolation_mode_to_cvcuda_interp[2] = cvcuda.Interp.LINEAR + _interpolation_mode_to_cvcuda_interp[3] = cvcuda.Interp.CUBIC + _interpolation_mode_to_cvcuda_interp[4] = cvcuda.Interp.BOX + _interpolation_mode_to_cvcuda_interp[5] = cvcuda.Interp.HAMMING + _interpolation_mode_to_cvcuda_interp[1] = cvcuda.Interp.LANCZOS + + interp = _interpolation_mode_to_cvcuda_interp.get(interpolation) + if interp is None: + raise ValueError(f"Interpolation mode {interpolation} is not supported with CV-CUDA") + + return interp