π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
[Fix] MotionBlur bug fix and doctest update (#782)
shijianjianac5f8fe94da8
diff --git a/Makefile b/Makefileindex e76033447..7c6e31f1c 100644--- a/Makefile+++ b/Makefile@@ -39,7 +39,7 @@ autopep8: FORCEautopep8 --in-place --aggressive --recursive kornia/ test/ examples/doctest:- pytest -v --doctest-modules kornia/color kornia/augmentation #... etc+ pytest -v --doctest-modules korniadocstyle: FORCEpydocstyle kornia/diff --git a/kornia/augmentation/augmentation.py b/kornia/augmentation/augmentation.pyindex a9b52cae3..bb0a265c6 100644--- a/kornia/augmentation/augmentation.py+++ b/kornia/augmentation/augmentation.py@@ -913,11 +913,11 @@ class RandomMotionBlur(AugmentationBase2D):>>> input = torch.ones(1, 1, 5, 5)>>> motion_blur = RandomMotionBlur(3, 35., 0.5, p=1.)>>> motion_blur(input)- tensor([[[[-0.5761, 1.0000, 1.0000, 1.0000, 1.9094],- [-0.5761, 1.0000, 1.0000, 1.0000, 1.9094],- [-0.5761, 1.0000, 1.0000, 1.0000, 1.9094],- [-0.5761, 1.0000, 1.0000, 1.0000, 1.9094],- [-0.5761, 1.0000, 1.0000, 1.0000, 1.9094]]]])+ tensor([[[[0.5773, 1.0000, 1.0000, 1.0000, 0.7561],+ [0.5773, 1.0000, 1.0000, 1.0000, 0.7561],+ [0.5773, 1.0000, 1.0000, 1.0000, 0.7561],+ [0.5773, 1.0000, 1.0000, 1.0000, 0.7561],+ [0.5773, 1.0000, 1.0000, 1.0000, 0.7561]]]])"""def __init__(diff --git a/kornia/augmentation/augmentation3d.py b/kornia/augmentation/augmentation3d.pyindex 802ffeeb1..0d731efe5 100644--- a/kornia/augmentation/augmentation3d.py+++ b/kornia/augmentation/augmentation3d.py@@ -471,23 +471,23 @@ class RandomMotionBlur3D(AugmentationBase3D):>>> input = torch.rand(1, 1, 3, 5, 5)>>> motion_blur = RandomMotionBlur3D(3, 35., 0.5, p=1.)>>> motion_blur(input)- tensor([[[[[ 0.1654, 5.0626, 3.7446, 6.8393, 3.5563],- [-5.0999, 2.1964, 2.4311, -1.8043, 1.4908],- [-3.2720, -2.1332, 2.1459, 1.7491, 1.3186],- [-2.6045, 5.2450, 6.0367, 1.0320, 6.7205],- [-4.5962, -5.2259, -0.9809, -1.6601, 0.1398]],+ tensor([[[[[0.1654, 0.4772, 0.2004, 0.3566, 0.2613],+ [0.4557, 0.3131, 0.4809, 0.2574, 0.2696],+ [0.2721, 0.5998, 0.3956, 0.5363, 0.1541],+ [0.3006, 0.4773, 0.6395, 0.2856, 0.3989],+ [0.4491, 0.5595, 0.1836, 0.3811, 0.1398]],<BLANKLINE>- [[ 0.1843, 2.6303, 7.0769, 1.3952, 2.1699],- [-6.4852, 0.3011, 0.3557, 4.5564, 5.5316],- [-6.4329, 2.8427, 0.2914, 3.6307, 0.4988],- [-1.2635, -4.5109, 1.3771, 0.8912, 2.1555],- [-1.6038, -3.7698, 0.0352, -0.8663, 0.1607]],+ [[0.1843, 0.4240, 0.3370, 0.1231, 0.2186],+ [0.4047, 0.3332, 0.1901, 0.5329, 0.3023],+ [0.3070, 0.3088, 0.4807, 0.4928, 0.2590],+ [0.2416, 0.4614, 0.7091, 0.5237, 0.1433],+ [0.1582, 0.4577, 0.2749, 0.1369, 0.1607]],<BLANKLINE>- [[ 0.2733, 1.8909, 4.7292, 1.0408, 1.4417],- [-6.8248, 0.8740, 1.4280, -4.1784, 5.0158],- [-3.8589, 2.7687, 2.9419, 3.2143, 6.3996],- [-4.7014, -0.3668, -1.8947, 0.1953, 7.2572],- [-3.5506, -4.1522, -5.3692, -6.4713, 0.3117]]]]])+ [[0.2733, 0.4040, 0.4396, 0.2284, 0.3319],+ [0.3856, 0.6730, 0.4624, 0.3878, 0.3076],+ [0.4307, 0.4217, 0.2977, 0.5086, 0.5406],+ [0.3686, 0.2778, 0.5228, 0.7592, 0.6455],+ [0.2033, 0.3014, 0.4898, 0.6164, 0.3117]]]]])"""def __init__(diff --git a/kornia/filters/kernels.py b/kornia/filters/kernels.pyindex 905951561..e76e2bcf2 100644--- a/kornia/filters/kernels.py+++ b/kornia/filters/kernels.py@@ -622,21 +622,20 @@ def get_motion_kernel2d(kernel_size: int, angle: Union[torch.Tensor, float],torch.Tensor: the motion blur kernel.Shape:- - Output: :math:`(ksize, ksize)`-- Examples:- get_motion_kernel2d(5, 0., 0.)- tensor([[0.0000, 0.0000, 0.0000, 0.0000, 0.0000],- [0.0000, 0.0000, 0.0000, 0.0000, 0.0000],- [0.2000, 0.2000, 0.2000, 0.2000, 0.2000],- [0.0000, 0.0000, 0.0000, 0.0000, 0.0000],- [0.0000, 0.0000, 0.0000, 0.0000, 0.0000]])- get_motion_kernel2d(3, 215., -0.5)- tensor([[0.0000, 0.0412, 0.0732],- [0.1920, 0.3194, 0.0804],- [0.2195, 0.0743, 0.0000]])+ - Output: :math:`(B, ksize, ksize)`++ Examples::+ >>> get_motion_kernel2d(5, 0., 0.)+ tensor([[[0.0000, 0.0000, 0.0000, 0.0000, 0.0000],+ [0.0000, 0.0000, 0.0000, 0.0000, 0.0000],+ [0.2000, 0.2000, 0.2000, 0.2000, 0.2000],+ [0.0000, 0.0000, 0.0000, 0.0000, 0.0000],+ [0.0000, 0.0000, 0.0000, 0.0000, 0.0000]]])+ >>> get_motion_kernel2d(3, 215., -0.5)+ tensor([[[0.0000, 0.0000, 0.1667],+ [0.0000, 0.3333, 0.0000],+ [0.5000, 0.0000, 0.0000]]])"""- # TODO: Enable doctest after #782device, dtype = _extract_device_dtype([angle if isinstance(angle, torch.Tensor) else None,direction if isinstance(direction, torch.Tensor) else None,@@ -670,8 +669,8 @@ def get_motion_kernel2d(kernel_size: int, angle: Union[torch.Tensor, float],kernel = torch.zeros((direction.size(0), *kernel_tuple), device=device, dtype=dtype)# Element-wise linspace- kernel[:, kernel_tuple[0] // 2, :] = torch.stack(- [(direction - (1 / (kernel_tuple[0] - 1)) * i) for i in range(kernel_tuple[0])], dim=-1)+ kernel[:, kernel_size // 2, :] = torch.stack(+ [(direction + ((1 - 2 * direction) / (kernel_size - 1)) * i) for i in range(kernel_size)], dim=-1)kernel = kernel.unsqueeze(1)# rotate (counterclockwise) kernel by given anglekernel = rotate(kernel, angle, mode='nearest', align_corners=True)@@ -687,8 +686,9 @@ def get_motion_kernel3d(kernel_size: int, angle: Union[torch.Tensor, Tuple[floatArgs:kernel_size (int): motion kernel width, height and depth. It should be odd and positive.- angle (tensor or float): Range of yaw (x-axis), pitch (y-axis), roll (z-axis) to select from.+ angle (tensor or tuple): Range of yaw (x-axis), pitch (y-axis), roll (z-axis) to select from.If tensor, it must be :math:`(B, 3)`.+ If tuple, it must be (yaw, pitch, raw).direction (float): forward/backward direction of the motion blur.Lower values towards -1.0 will point the motion blur towards the back (with angle provided via angle),while higher values towards 1.0 will point the motion blur forward. A value of 0.0 leads to a@@ -698,26 +698,44 @@ def get_motion_kernel3d(kernel_size: int, angle: Union[torch.Tensor, Tuple[floattorch.Tensor: the motion blur kernel.Shape:- - Output: :math:`(ksize, ksize)`+ - Output: :math:`(B, kernel_size, kernel_size, kernel_size)`Examples:- get_motion_kernel2d(5, 0., 0.)- tensor([[0.0000, 0.0000, 0.0000, 0.0000, 0.0000],- [0.0000, 0.0000, 0.0000, 0.0000, 0.0000],- [0.2000, 0.2000, 0.2000, 0.2000, 0.2000],- [0.0000, 0.0000, 0.0000, 0.0000, 0.0000],- [0.0000, 0.0000, 0.0000, 0.0000, 0.0000]])- get_motion_kernel2d(3, 215., -0.5)- tensor([[0.0000, 0.0412, 0.0732],- [0.1920, 0.3194, 0.0804],- [0.2195, 0.0743, 0.0000]])+ >>> get_motion_kernel3d(3, (0., 0., 0.), 0.)+ tensor([[[[0.0000, 0.0000, 0.0000],+ [0.0000, 0.0000, 0.0000],+ [0.0000, 0.0000, 0.0000]],+ <BLANKLINE>+ [[0.0000, 0.0000, 0.0000],+ [0.3333, 0.3333, 0.3333],+ [0.0000, 0.0000, 0.0000]],+ <BLANKLINE>+ [[0.0000, 0.0000, 0.0000],+ [0.0000, 0.0000, 0.0000],+ [0.0000, 0.0000, 0.0000]]]])+ >>> get_motion_kernel3d(3, (90., 90., 0.), -0.5)+ tensor([[[[0.0000, 0.0000, 0.0000],+ [0.0000, 0.0000, 0.0000],+ [0.0000, 0.5000, 0.0000]],+ <BLANKLINE>+ [[0.0000, 0.0000, 0.0000],+ [0.0000, 0.3333, 0.0000],+ [0.0000, 0.0000, 0.0000]],+ <BLANKLINE>+ [[0.0000, 0.1667, 0.0000],+ [0.0000, 0.0000, 0.0000],+ [0.0000, 0.0000, 0.0000]]]])"""- # TODO: Enable doctest after #782if not isinstance(kernel_size, int) or kernel_size % 2 == 0 or kernel_size < 3:raise TypeError(f"ksize must be an odd integer >= than 3. Got {kernel_size}.")+ device, dtype = _extract_device_dtype([+ angle if isinstance(angle, torch.Tensor) else None,+ direction if isinstance(direction, torch.Tensor) else None,+ ])+if not isinstance(angle, torch.Tensor):- angle = torch.tensor([angle])+ angle = torch.tensor([angle], device=device, dtype=dtype)angle = cast(torch.Tensor, angle)if angle.dim() == 1:@@ -725,7 +743,7 @@ def get_motion_kernel3d(kernel_size: int, angle: Union[torch.Tensor, Tuple[floatassert len(angle.shape) == 2 and angle.size(1) == 3, f"angle must be (B, 3). Got {angle}."if not isinstance(direction, torch.Tensor):- direction = torch.tensor([direction])+ direction = torch.tensor([direction], device=device, dtype=dtype)direction = cast(torch.Tensor, direction)if direction.dim() == 0:@@ -738,11 +756,11 @@ def get_motion_kernel3d(kernel_size: int, angle: Union[torch.Tensor, Tuple[floatkernel_tuple: Tuple[int, int, int] = (kernel_size, kernel_size, kernel_size)# direction from [-1, 1] to [0, 1] rangedirection = (torch.clamp(direction, -1., 1.) + 1.) / 2.- kernel = torch.zeros((direction.size(0), *kernel_tuple), dtype=torch.float)+ kernel = torch.zeros((direction.size(0), *kernel_tuple), device=device, dtype=dtype)# Element-wise linspace- kernel[:, kernel_tuple[0] // 2, kernel_tuple[0] // 2, :] = torch.stack(- [(direction - (1 / (kernel_tuple[0] - 1)) * i) for i in range(kernel_tuple[0])], dim=-1)+ kernel[:, kernel_size // 2, kernel_size // 2, :] = torch.stack(+ [(direction + ((1 - 2 * direction) / (kernel_size - 1)) * i) for i in range(kernel_size)], dim=-1)kernel = kernel.unsqueeze(1)# rotate (counterclockwise) kernel by given anglekernel = rotate3d(kernel, angle[:, 0], angle[:, 1], angle[:, 2], mode='nearest', align_corners=True)diff --git a/kornia/filters/motion.py b/kornia/filters/motion.pyindex 0e3b66f56..d0f9f8e47 100644--- a/kornia/filters/motion.py+++ b/kornia/filters/motion.py@@ -169,7 +169,7 @@ def motion_blur3d(>>> torch.allclose(out_1[0], out_1[1])True>>> # perform element-wise motion blur accross the batch- >>> out_1 = motion_blur3d(input, 5, torch.tensor([[0., 90., 90.], [90., 180., 0.]]), torch.tensor([1, -1]))+ >>> out_1 = motion_blur3d(input, 5, torch.tensor([[0., 90., 90.], [90., 180., 0.]]), torch.tensor([1., -1.]))>>> torch.allclose(out_1[0], out_1[1])False"""diff --git a/kornia/geometry/camera/pinhole.py b/kornia/geometry/camera/pinhole.pyindex 5b52c0611..faac2c854 100644--- a/kornia/geometry/camera/pinhole.py+++ b/kornia/geometry/camera/pinhole.py@@ -546,10 +546,11 @@ def homography_i_H_ref(pinhole_i, pinhole_ref):- Output: :math:`(N, 4, 4)`Example:- >>> pinhole_i = torch.rand(1, 12) # Nx12- >>> pinhole_ref = torch.rand(1, 12) # Nx12- >>> homography_i_H_ref(pinhole_i, pinhole_ref) # Nx4x4+ pinhole_i = torch.rand(1, 12) # Nx12+ pinhole_ref = torch.rand(1, 12) # Nx12+ homography_i_H_ref(pinhole_i, pinhole_ref) # Nx4x4"""+ # TODO: Add doctest once having `rtvec_to_pose`.assert len(pinhole_i.shape) == 2 and pinhole_i.shape[1] == 12, pinhole.shapeassert pinhole_i.shape == pinhole_ref.shape, pinhole_ref.shapediff --git a/kornia/geometry/transform/crop/crop2d.py b/kornia/geometry/transform/crop/crop2d.pyindex 7a0c3728c..95824013f 100644--- a/kornia/geometry/transform/crop/crop2d.py+++ b/kornia/geometry/transform/crop/crop2d.py@@ -353,14 +353,14 @@ def bbox_generator(>>> height = torch.tensor([7, 4])>>> bbox_generator(x_start, y_start, width, height)tensor([[[0, 1],- [5, 1],- [5, 8],- [0, 8]],+ [4, 1],+ [4, 7],+ [0, 7]],<BLANKLINE>[[1, 0],- [4, 0],- [4, 4],- [1, 4]]])+ [3, 0],+ [3, 3],+ [1, 3]]])"""assert x_start.shape == y_start.shape and x_start.dim() in [0, 1], \f"`x_start` and `y_start` must be a scalar or (B,). Got {x_start}, {y_start}."diff --git a/kornia/utils/helpers.py b/kornia/utils/helpers.pyindex b8edb8390..89e284854 100644--- a/kornia/utils/helpers.py+++ b/kornia/utils/helpers.py@@ -7,6 +7,9 @@ def _extract_device_dtype(tensor_list: List[Optional[torch.Tensor]]) -> Tuple[to"""Check if all the input tensors are in the same device.If so, it would return a tuple of (device, dtype). Default: (cpu, ``get_default_dtype()``).++ Returns:+ [torch.device, torch.dtype]"""device, dtype = None, Nonefor tensor in tensor_list:diff --git a/test/augmentation/test_motionblur.py b/test/augmentation/test_motionblur.pyindex 5888840fb..1ebbc00fe 100644--- a/test/augmentation/test_motionblur.py+++ b/test/augmentation/test_motionblur.py@@ -8,11 +8,15 @@ from torch.testing import assert_allclosefrom torch.autograd import gradcheckimport kornia-import kornia.testing as utils # test utils+from kornia.testing import tensor_to_gradcheck_varfrom kornia.augmentation import (RandomMotionBlur,RandomMotionBlur3D,)+from kornia.filters import (+ motion_blur,+ motion_blur3d,+)class TestRandomMotionBlur:@@ -22,7 +26,7 @@ class TestRandomMotionBlur:@pytest.mark.xfail(reason="might fail under windows OS due to printing preicision.")def test_smoke(self, device):f = RandomMotionBlur(kernel_size=(3, 5), angle=(10, 30), direction=0.5)- repr = "RandomMotionBlur(kernel_size=(3, 5), angle=tensor([10., 30.]), direction=tensor([-0.5000, 0.5000]), "\+ repr = "RandomMotionBlur(kernel_size=(3, 5), angle=tensor([10., 30.]), direction=tensor([-0.5000, 0.5000]), "\"border_type='constant', p=0.5, p_batch=1.0, same_on_batch=False, return_transform=False)"assert str(f) == repr@@ -32,7 +36,9 @@ class TestRandomMotionBlur:def test_random_motion_blur(self, same_on_batch, return_transform, p, device, dtype):f = RandomMotionBlur(kernel_size=(3, 5), angle=(10, 30), direction=0.5,same_on_batch=same_on_batch, return_transform=return_transform, p=p)- input = torch.randn(1, 3, 5, 6).repeat(2, 1, 1, 1)+ torch.manual_seed(0)+ batch_size = 2+ input = torch.randn(1, 3, 5, 6).repeat(batch_size, 1, 1, 1)output = f(input)@@ -49,10 +55,25 @@ class TestRandomMotionBlur:else:assert not torch.allclose(output[0], output[1], rtol=1e-4, atol=1e-4)+ assert output.shape == torch.Size([batch_size, 3, 5, 6])++ @pytest.mark.parametrize("input_shape", [(1, 1, 5, 5), (2, 1, 5, 5)])+ def test_against_functional(self, input_shape):++ input = torch.randn(*input_shape)++ f = RandomMotionBlur(kernel_size=(3, 5), angle=(10, 30), direction=0.5, p=1.)+ output = f(input)++ expected = motion_blur(input, f._params['ksize_factor'].unique().item(), f._params['angle_factor'],+ f._params['direction_factor'], f.border_type.name.lower())++ assert_allclose(output, expected, rtol=1e-4, atol=1e-4)+def test_gradcheck(self, device):torch.manual_seed(0) # for random reproductibilityinp = torch.rand((1, 3, 11, 7)).to(device)- inp = utils.tensor_to_gradcheck_var(inp) # to var+ inp = tensor_to_gradcheck_var(inp) # to var# TODO: Gradcheck for param random gen failed. Suspect get_motion_kernel2d issue.params = {'batch_prob': torch.tensor([True]),@@ -72,7 +93,7 @@ class TestRandomMotionBlur3D:def test_smoke(self, device, dtype):f = RandomMotionBlur3D(kernel_size=(3, 5), angle=(10, 30), direction=0.5)repr = "RandomMotionBlur3D(kernel_size=(3, 5), angle=tensor([[10., 30.],"\- "\n [10., 30.],\n [10., 30.]]), direction=tensor([-0.5000, 0.5000]), " \+ "\n [10., 30.],\n [10., 30.]]), direction=tensor([-0.5000, 0.5000]), " \"border_type='constant', p=0.5, p_batch=1.0, same_on_batch=False, return_transform=False)"assert str(f) == repr@@ -82,7 +103,8 @@ class TestRandomMotionBlur3D:def test_random_motion_blur(self, same_on_batch, return_transform, p, device, dtype):f = RandomMotionBlur3D(kernel_size=(3, 5), angle=(10, 30), direction=0.5,same_on_batch=same_on_batch, return_transform=return_transform, p=p)- input = torch.randn(1, 3, 5, 6, 7).repeat(2, 1, 1, 1, 1)+ batch_size = 2+ input = torch.randn(1, 3, 5, 6, 7, device=device, dtype=dtype).repeat(batch_size, 1, 1, 1, 1)output = f(input)@@ -99,10 +121,25 @@ class TestRandomMotionBlur3D:else:assert not torch.allclose(output[0], output[1], rtol=1e-4, atol=1e-4)+ assert output.shape == torch.Size([batch_size, 3, 5, 6, 7])++ @pytest.mark.parametrize("input_shape", [(1, 1, 5, 6, 7), (2, 1, 5, 6, 7)])+ def test_against_functional(self, input_shape):++ input = torch.randn(*input_shape)++ f = RandomMotionBlur3D(kernel_size=(3, 5), angle=(10, 30), direction=0.5, p=1.)+ output = f(input)++ expected = motion_blur3d(input, f._params['ksize_factor'].unique().item(), f._params['angle_factor'],+ f._params['direction_factor'], f.border_type.name.lower())++ assert_allclose(output, expected, rtol=1e-4, atol=1e-4)+def test_gradcheck(self, device, dtype):torch.manual_seed(0) # for random reproductibilityinp = torch.rand((1, 3, 11, 7)).to(device)- inp = utils.tensor_to_gradcheck_var(inp) # to var+ inp = tensor_to_gradcheck_var(inp) # to varparams = {'batch_prob': torch.tensor([True]),'ksize_factor': torch.tensor([31]),diff --git a/test/utils/test_helpers.py b/test/utils/test_helpers.pynew file mode 100644index 000000000..40ee9508b--- /dev/null+++ b/test/utils/test_helpers.py@@ -0,0 +1,36 @@+import pytest++import torch++from kornia.utils import _extract_device_dtype++[email protected]("tensor_list,out_device,out_dtype,will_throw_error", [+ ([], torch.device('cpu'), torch.get_default_dtype(), False),+ ([None, None], torch.device('cpu'), torch.get_default_dtype(), False),+ ([torch.tensor(0, device='cpu', dtype=torch.float16), None], torch.device('cpu'), torch.float16, False),+ ([torch.tensor(0, device='cpu', dtype=torch.float32), None], torch.device('cpu'), torch.float32, False),+ ([torch.tensor(0, device='cpu', dtype=torch.float64), None], torch.device('cpu'), torch.float64, False),+ ([torch.tensor(0, device='cpu', dtype=torch.float16)] * 2, torch.device('cpu'), torch.float16, False),+ ([torch.tensor(0, device='cpu', dtype=torch.float32)] * 2, torch.device('cpu'), torch.float32, False),+ ([torch.tensor(0, device='cpu', dtype=torch.float64)] * 2, torch.device('cpu'), torch.float64, False),+ ([torch.tensor(0, device='cpu', dtype=torch.float16),+ torch.tensor(0, device='cpu', dtype=torch.float64)], None, None, True),+ ([torch.tensor(0, device='cpu', dtype=torch.float32),+ torch.tensor(0, device='cpu', dtype=torch.float64)], None, None, True),+ ([torch.tensor(0, device='cpu', dtype=torch.float16),+ torch.tensor(0, device='cpu', dtype=torch.float32)], None, None, True),+])+def test_extract_device_dtype(tensor_list, out_device, out_dtype, will_throw_error):+ # Add GPU tests when GPU testing avaliable+ if torch.cuda.is_available():+ import warnings+ warnings.warn("Add GPU tests.")++ if will_throw_error:+ with pytest.raises(ValueError):+ _extract_device_dtype(tensor_list)+ else:+ device, dtype = _extract_device_dtype(tensor_list)+ assert device == out_device+ assert dtype == out_dtype