π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
Speed-up warp_affine and fix bugs in RandomAffine [WIP: to add tests] (#474)
Dmytro Mishkin02d807662d95
diff --git a/Makefile b/Makefileindex 7c1d6e79e..e298204e7 100644--- a/Makefile+++ b/Makefile@@ -25,6 +25,9 @@ build-docs: FORCEinstall: FORCEpython setup.py install++benchmark:+ for f in test/performance/*.py ; do python -utt $${f}; doneuninstall: FORCEpip uninstall korniadiff --git a/docs/source/geometry.conversions.rst b/docs/source/geometry.conversions.rstindex 03cfabe33..bfc9a35e7 100644--- a/docs/source/geometry.conversions.rst+++ b/docs/source/geometry.conversions.rst@@ -7,6 +7,7 @@ kornia.geometry.conversions.. autofunction:: deg2rad.. autofunction:: convert_points_from_homogeneous.. autofunction:: convert_points_to_homogeneous+.. autofunction:: convert_affinematrix_to_homography.. autofunction:: rotation_matrix_to_angle_axis.. autofunction:: rotation_matrix_to_quaternion.. autofunction:: quaternion_to_angle_axisdiff --git a/kornia/augmentation/functional.py b/kornia/augmentation/functional.pyindex 7a8dc91a7..a38538c82 100644--- a/kornia/augmentation/functional.py+++ b/kornia/augmentation/functional.py@@ -5,7 +5,7 @@ import torch.nn as nnfrom kornia.geometry.transform.flips import hflip, vflipfrom kornia.geometry.transform import (- get_perspective_transform, warp_perspective, center_crop, rotate, crop_by_boxes)+ get_perspective_transform, warp_perspective, center_crop, rotate, crop_by_boxes, warp_affine)from kornia.color.adjust import AdjustBrightness, AdjustContrast, AdjustSaturation, AdjustHuefrom kornia.color.gray import rgb_to_grayscalefrom kornia.geometry.transform.affwarp import _compute_rotation_matrix, _compute_tensor_center@@ -446,8 +446,7 @@ def _apply_affine(input: torch.Tensor,height, width = x_data.shape[-2:]transform: torch.Tensor = params['transform'].to(device, dtype)-- out_data: torch.Tensor = warp_perspective(x_data, transform, (height, width))+ out_data: torch.Tensor = warp_affine(x_data, transform[:, :2, :], (height, width))if return_transform:return out_data.view_as(input), transformdiff --git a/kornia/augmentation/param_gen.py b/kornia/augmentation/param_gen.pyindex d5d58df43..9692e59a1 100644--- a/kornia/augmentation/param_gen.py+++ b/kornia/augmentation/param_gen.py@@ -7,6 +7,7 @@ from torch.distributions import Uniformfrom kornia.geometry import pifrom kornia.geometry.transform import get_rotation_matrix2d+from kornia.geometry.conversions import convert_affinematrix_to_homographyUnionType = Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]@@ -258,12 +259,43 @@ def _random_rotation_gen(batch_size: int, degrees: FloatUnionType) -> Dict[str,return params+def _compose_affine_matrix_3x3(translations: torch.Tensor,+ center: torch.Tensor,+ scale: torch.Tensor,+ angle: torch.Tensor,+ sx: Optional[torch.Tensor] = None,+ sy: Optional[torch.Tensor] = None) -> torch.Tensor:+ r"""Composes affine matrix Bx3x3 from the components+ Returns:+ torch.Tensor: params to be passed to the affine transformation.+ """+ transform: torch.Tensor = get_rotation_matrix2d(center, -angle, scale)+ transform[..., 2] += translations # tx/ty+ # pad transform to get Bx3x3+ transform_h = convert_affinematrix_to_homography(transform)+ if sx is not None:+ x, y = torch.split(center, 1, dim=-1)+ x = x.view(-1)+ y = y.view(-1)+ sx_tan = torch.tan(sx) # type: ignore+ sy_tan = torch.tan(sy) # type: ignore+ zeros = torch.zeros_like(sx) # type: ignore+ ones = torch.ones_like(sx) # type: ignore+ shear_mat = torch.stack([ones, -sx_tan, sx_tan * x, # type: ignore # noqa: E241+ -sy_tan, ones + sx_tan * sy_tan, sy_tan * (-sx_tan * x + y)], # noqa: E241+ dim=-1).view(-1, 2, 3)+ shear_mat = convert_affinematrix_to_homography(shear_mat)+ transform_h = transform_h @ shear_mat+ return transform_h++def _get_random_affine_params(batch_size: int, height: int, width: int,degrees: TupleFloat, translate: Optional[TupleFloat],scales: Optional[TupleFloat], shears: Optional[TupleFloat],) -> torch.Tensor:- r"""Get parameters for affine transformation. The returned matrix is Bx3x3.+ r"""Get parameters for affine transformation random generation.+ The returned matrix is Bx3x3.Returns:torch.Tensor: params to be passed to the affine transformation.@@ -276,11 +308,6 @@ def _get_random_affine_params(else:scale = torch.ones(batch_size)- if shears is not None:- shear = Uniform(shears[0], shears[1]).rsample((batch_size,))- else:- shear = torch.zeros(batch_size)-if translate is not None:max_dx: float = translate[0] * widthmax_dy: float = translate[1] * height@@ -292,18 +319,22 @@ def _get_random_affine_params(translations = torch.zeros(batch_size, 2)center: torch.Tensor = torch.tensor(- [width, height], dtype=torch.float32).view(1, 2) / 2+ [width, height], dtype=torch.float32).view(1, 2) / 2. - 0.5center = center.expand(batch_size, -1)-+ if shears is not None:+ shears = math.radians(shears[0]), math.radians(shears[1])+ sx = Uniform(shears[0], shears[1]).rsample((batch_size,))+ sy = Uniform(shears[0], shears[1]).rsample((batch_size,))+ ones = torch.ones_like(sx)+ else:+ sx = sy = None# concatenate transforms- transform: torch.Tensor = get_rotation_matrix2d(center, angle, scale)- transform[..., 2] += translations # tx/ty- transform[..., 0, 1] += shear- transform[..., 1, 0] += shear-- # pad transform to get Bx3x3- transform_h = torch.nn.functional.pad(transform, [0, 0, 0, 1], value=0.)- transform_h[..., -1, -1] += 1.0+ transform_h = _compose_affine_matrix_3x3(translations,+ center,+ scale,+ angle,+ sx,+ sy)return transform_hdiff --git a/kornia/geometry/conversions.py b/kornia/geometry/conversions.pyindex a8a562711..239627b87 100644--- a/kornia/geometry/conversions.py+++ b/kornia/geometry/conversions.py@@ -9,6 +9,7 @@ __all__ = ["deg2rad","convert_points_from_homogeneous","convert_points_to_homogeneous",+ "convert_affinematrix_to_homography","angle_axis_to_rotation_matrix","angle_axis_to_quaternion","rotation_matrix_to_angle_axis",@@ -119,6 +120,25 @@ def convert_points_to_homogeneous(points: torch.Tensor) -> torch.Tensor:return torch.nn.functional.pad(points, [0, 1], "constant", 1.0)+def convert_affinematrix_to_homography(A: torch.Tensor) -> torch.Tensor:+ r"""Function that converts batch of affine matrices from [Bx2x3] to [Bx3x3].++ Examples::++ >>> input = torch.rand(2, 2, 3) # Bx2x3+ >>> output = kornia.convert_affinematrix_to_homography(input) # Bx3x3+ """+ if not isinstance(A, torch.Tensor):+ raise TypeError("Input type is not a torch.Tensor. Got {}".format(+ type(A)))+ if not (len(A.shape) == 3 and A.shape[-2:] == (2, 3)):+ raise ValueError("Input matrix must be a Bx2x3 tensor. Got {}"+ .format(A.shape))+ H: torch.Tensor = torch.nn.functional.pad(A, [0, 0, 0, 1], "constant", value=0.)+ H[..., -1, -1] += 1.0+ return H++def angle_axis_to_rotation_matrix(angle_axis: torch.Tensor) -> torch.Tensor:r"""Convert 3d vector of axis-angle rotation to 3x3 rotation matrixdiff --git a/kornia/geometry/transform/crop.py b/kornia/geometry/transform/crop.pyindex e1aeb9703..8b79ce551 100644--- a/kornia/geometry/transform/crop.py+++ b/kornia/geometry/transform/crop.py@@ -3,7 +3,7 @@ from typing import Tuple, Unionimport torchfrom kornia.geometry.transform.imgwarp import (- warp_perspective, get_perspective_transform+ warp_perspective, get_perspective_transform, warp_affine)__all__ = [@@ -71,7 +71,7 @@ def crop_and_resize(tensor: torch.Tensor, boxes: torch.Tensor, size: Tuple[int,[dst_w - 1, 0],[dst_w - 1, dst_h - 1],[0, dst_h - 1],- ]]).repeat(points_src.shape[0], 1, 1)+ ]], device=tensor.device).expand(points_src.shape[0], -1, -1)return crop_by_boxes(tensor, points_src, points_dst, return_transform=return_transform)@@ -134,7 +134,7 @@ def center_crop(tensor: torch.Tensor, size: Tuple[int, int],[end_x, start_y],[end_x, end_y],[start_x, end_y],- ]])+ ]], device=tensor.device)# [y, x] destination# top-left, top-right, bottom-right, bottom-left@@ -143,7 +143,7 @@ def center_crop(tensor: torch.Tensor, size: Tuple[int, int],[dst_w - 1, 0],[dst_w - 1, dst_h - 1],[0, dst_h - 1],- ]]).repeat(points_src.shape[0], 1, 1)+ ]], device=tensor.device).expand(points_src.shape[0], -1, -1)return crop_by_boxes(tensor, points_src, points_dst, return_transform=return_transform)@@ -168,8 +168,8 @@ def crop_by_boxes(tensor, src_box, dst_box,dst_trans_src = dst_trans_src.expand(tensor.shape[0], -1, -1)bbox = _infer_bounding_box(dst_box)- patches: torch.Tensor = warp_perspective(- tensor, dst_trans_src, (int(bbox[0].int().data.item()), int(bbox[1].int().data.item())))+ patches: torch.Tensor = warp_affine(+ tensor, dst_trans_src[:, :2, :], (int(bbox[0].int().data.item()), int(bbox[1].int().data.item())))# return in the original shapeif is_unbatched:diff --git a/kornia/geometry/transform/imgwarp.py b/kornia/geometry/transform/imgwarp.pyindex f1abfd727..a2546bbe9 100644--- a/kornia/geometry/transform/imgwarp.py+++ b/kornia/geometry/transform/imgwarp.py@@ -7,7 +7,7 @@ import korniafrom kornia.geometry.warp.homography_warper import homography_warp# TODO: move to utils or conversionsfrom kornia.geometry.conversions import (- deg2rad, normalize_pixel_coordinates+ deg2rad, normalize_pixel_coordinates, convert_affinematrix_to_homography)__all__ = [@@ -169,15 +169,21 @@ def warp_affine(src: torch.Tensor, M: torch.Tensor,if not (len(M.shape) == 3 or M.shape[-2:] == (2, 3)):raise ValueError("Input M must be a Bx2x3 tensor. Got {}".format(src.shape))-+ B, C, H, W = src.size()+ dsize_src = (H, W)+ out_size = dsize# we generate a 3x3 transformation matrix from 2x3 affine- M_3x3: torch.Tensor = F.pad(M, [0, 0, 0, 1, 0, 0],- mode="constant", value=0)- M_3x3[:, 2, 2] += 1.0-- # launches the warper- h, w = src.shape[-2:]- return transform_warp_impl(src, M_3x3, (h, w), dsize, flags, padding_mode)+ M_3x3: torch.Tensor = convert_affinematrix_to_homography(M)+ dst_norm_trans_src_norm: torch.Tensor = src_norm_to_dst_norm(+ M_3x3, dsize_src, out_size)+ src_norm_trans_dst_norm = torch.inverse(dst_norm_trans_src_norm)+ grid = F.affine_grid(src_norm_trans_dst_norm[:, :2, :], # type: ignore+ [B, C, out_size[0], out_size[1]],+ align_corners=True)+ return F.grid_sample(src, grid, # type: ignore+ align_corners=True,+ mode=flags,+ padding_mode=padding_mode)def get_perspective_transform(src, dst):@@ -476,11 +482,9 @@ def invert_affine_transform(matrix: torch.Tensor) -> torch.Tensor:if not torch.is_tensor(matrix):raise TypeError("Input matrix type is not a torch.Tensor. Got {}".format(type(matrix)))- if not (len(matrix.shape) == 3 or matrix.shape[-2:] == (2, 3)):+ if not (len(matrix.shape) == 3 and matrix.shape[-2:] == (2, 3)):raise ValueError("Input matrix must be a Bx2x3 tensor. Got {}".format(matrix.shape))- matrix_tmp: torch.Tensor = F.pad(matrix, [0, 0, 0, 1], "constant", 0.0)- matrix_tmp[..., 2, 2] += 1.0-+ matrix_tmp: torch.Tensor = convert_affinematrix_to_homography(matrix)matrix_inv: torch.Tensor = torch.inverse(matrix_tmp)return matrix_inv[..., :2, :3]diff --git a/test/augmentation/test_perspective.py b/test/augmentation/test_perspective.pyindex 23b56af62..cf4cb8566 100644--- a/test/augmentation/test_perspective.py+++ b/test/augmentation/test_perspective.py@@ -8,6 +8,7 @@ import korniaimport kornia.augmentation.functional as Fimport kornia.testing as utils # test utilsfrom test.common import device+import kornia.augmentation.param_gen as pgclass TestPerspective:@@ -134,6 +135,54 @@ class TestRandomAffine:assert out[0].shape == x_data.shapeassert out[1].shape == (1, 3, 3)+ def test_compose_affine_matrix_3x3(self, device):+ """ To get parameters:+ import torchvision as tv+ from PIL import Image+ from torch import Tensor as T+ import math+ import random+ img_size = (96,96)+ seed = 42+ torch.manual_seed(seed)+ torch.cuda.manual_seed(seed)+ torch.cuda.manual_seed_all(seed) # if you are using multi-GPU.+ np.random.seed(seed) # Numpy module.+ random.seed(seed) # Python random module.+ torch.manual_seed(seed)+ tfm = tv.transforms.RandomAffine(degrees=(-25.0,25.0),+ scale=(0.6, 1.4) ,+ translate=(0, 0.1),+ shear=(-25., 25., -20., 20.))+ angle, translations, scale, shear = tfm.get_params(tfm.degrees, tfm.translate,+ tfm.scale, tfm.shear, img_size)+ print (angle, translations, scale, shear)+ output_size = img_size+ center = (img.size[0] * 0.5 + 0.5, img.size[1] * 0.5 + 0.5)++ matrix = tv.transforms.functional._get_inverse_affine_matrix(center, angle, translations, scale, shear)+ matrix = np.array(matrix).reshape(2,3)+ print (matrix)+ """+ from torch import Tensor as T+ import math+ batch_size, ch, height, width = 1, 1, 96, 96+ angle, translations = 6.971339922894188, (0.0, -4.0)+ scale, shear = 0.7785685905190581, [11.823560708200617, 7.06797949691645]+ matrix_expected = T([[1.27536969, 4.26828945e-01, -3.23493180e+01],+ [2.18297196e-03, 1.29424165e+00, -9.19962753e+00]])+ center = T([float(width), float(height)]).view(1, 2) / 2. + 0.5+ center = center.expand(batch_size, -1)+ matrix_kornia = pg._compose_affine_matrix_3x3(+ T(translations).view(-1, 2),+ center,+ T([scale]).view(-1),+ T([angle]).view(-1),+ T([math.radians(shear[0])]).view(-1, 1),+ T([math.radians(shear[1])]).view(-1, 1))+ matrix_kornia = matrix_kornia.inverse()[0, :2].detach().cpu()+ assert_allclose(matrix_kornia, matrix_expected)+def test_gradcheck(self, device):input = torch.rand(1, 2, 5, 7).to(device)input = utils.tensor_to_gradcheck_var(input) # to vardiff --git a/test/geometry/test_conversions.py b/test/geometry/test_conversions.pyindex 472e75ec7..55ef4db7d 100644--- a/test/geometry/test_conversions.py+++ b/test/geometry/test_conversions.py@@ -436,6 +436,46 @@ class TestConvertPointsToHomogeneous:assert_allclose(actual, expected)+class TestConvertAtoH:+ def test_convert_points(self, device):+ # generate input data+ A = torch.tensor([+ [1., 0., 0.],+ [0., 1., 0.],+ ]).to(device).view(1, 2, 3)++ expected = torch.tensor([+ [1., 0., 0.],+ [0., 1., 0.],+ [0., 0., 1.],+ ]).to(device).view(1, 3, 3)++ # to euclidean+ H = kornia.geometry.conversions.convert_affinematrix_to_homography(A)+ assert_allclose(H, expected)++ @pytest.mark.parametrize("batch_shape", [+ (10, 2, 3), (16, 2, 3)])+ def test_gradcheck(self, device, batch_shape):+ points_h = torch.rand(batch_shape).to(device)++ # evaluate function gradient+ points_h = tensor_to_gradcheck_var(points_h) # to var+ assert gradcheck(kornia.convert_affinematrix_to_homography, (points_h,),+ raise_exception=True)++ @pytest.mark.skip(reason="turn off all jit for a while")+ def test_jit(self, device):+ op = kornia.convert_affinematrix_to_homography+ op_script = torch.jit.script(op)++ points_h = torch.zeros(1, 2, 3).to(device)+ actual = op_script(points_h)+ expected = op(points_h)++ assert_allclose(actual, expected)++class TestConvertPointsFromHomogeneous:def test_convert_points(self, device):# generate input datadiff --git a/test/geometry/transform/test_imgwarp.py b/test/geometry/transform/test_imgwarp.pyindex 310f02f14..afbfc39e7 100644--- a/test/geometry/transform/test_imgwarp.py+++ b/test/geometry/transform/test_imgwarp.py@@ -404,7 +404,7 @@ class TestRemap:class TestInvertAffineTransform:def test_smoke(self, device):- matrix = torch.eye(2, 3).to(device)+ matrix = torch.eye(2, 3).to(device)[None]matrix_inv = kornia.invert_affine_transform(matrix)assert_allclose(matrix, matrix_inv)@@ -434,7 +434,7 @@ class TestInvertAffineTransform:assert_allclose(matrix_inv, expected)def test_gradcheck(self, device):- matrix = torch.eye(2, 3).to(device)+ matrix = torch.eye(2, 3).to(device)[None]matrix = utils.tensor_to_gradcheck_var(matrix) # to varassert gradcheck(kornia.invert_affine_transform, (matrix,),raise_exception=True)diff --git a/test/performance/test_imgwarp_speed.py b/test/performance/test_imgwarp_speed.pynew file mode 100644index 000000000..584fb2c84--- /dev/null+++ b/test/performance/test_imgwarp_speed.py@@ -0,0 +1,23 @@+import torch+import kornia as kornia+from time import time+++devices = [torch.device('cpu'), torch.device('cuda:0')]+shapes = [(512, 3, 256, 256), (256, 1, 64, 64)]+PSs = [224, 32]++if __name__ == '__main__':+ print("Benchmarking warp_affine")+ for device in devices:+ for input_shape in shapes:+ for PS in PSs:+ BS = input_shape[0]+ inpt = torch.rand(input_shape).to(device)+ As = torch.eye(3).unsqueeze(0).repeat(BS, 1, 1)[:, :2, :].to(device)+ As += 0.1 * torch.rand(As.size()).to(device)+ torch.cuda.synchronize()+ t = time()+ kornia_wa = kornia.warp_affine(inpt, As, (PS, PS))+ print(f"inp={input_shape}, PS={PS}, dev={device}, {time() - t}, sec")+ torch.cuda.synchronize()