π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
Make sharpness output channel nums as input (#783)
shijianjian177bbe474587
diff --git a/kornia/augmentation/augmentation.py b/kornia/augmentation/augmentation.pyindex bf7afe7f3..d6f250c25 100644--- a/kornia/augmentation/augmentation.py+++ b/kornia/augmentation/augmentation.py@@ -1101,21 +1101,9 @@ class RandomSharpness(AugmentationBase2D):>>> sharpness = RandomSharpness(1., p=1.)>>> sharpness(input)tensor([[[[0.4963, 0.7682, 0.0885, 0.1320, 0.3074],- [0.6341, 0.7720, 0.9537, 0.7566, 0.6323],- [0.3489, 0.7325, 0.5629, 0.6284, 0.2939],- [0.5185, 0.8648, 0.9106, 0.6249, 0.2823],- [0.6816, 0.9152, 0.3971, 0.8742, 0.4194]],- <BLANKLINE>- [[0.4963, 0.7682, 0.0885, 0.1320, 0.3074],- [0.6341, 0.7720, 0.9537, 0.7566, 0.6323],- [0.3489, 0.7325, 0.5629, 0.6284, 0.2939],- [0.5185, 0.8648, 0.9106, 0.6249, 0.2823],- [0.6816, 0.9152, 0.3971, 0.8742, 0.4194]],- <BLANKLINE>- [[0.4963, 0.7682, 0.0885, 0.1320, 0.3074],- [0.6341, 0.7720, 0.9537, 0.7566, 0.6323],- [0.3489, 0.7325, 0.5629, 0.6284, 0.2939],- [0.5185, 0.8648, 0.9106, 0.6249, 0.2823],+ [0.6341, 0.7059, 0.9403, 0.6860, 0.6323],+ [0.3489, 0.6549, 0.4361, 0.5206, 0.2939],+ [0.5185, 0.8256, 0.8847, 0.5161, 0.2823],[0.6816, 0.9152, 0.3971, 0.8742, 0.4194]]]])"""diff --git a/kornia/enhance/adjust.py b/kornia/enhance/adjust.pyindex 2141f6c7a..5bd220ab0 100644--- a/kornia/enhance/adjust.py+++ b/kornia/enhance/adjust.py@@ -396,7 +396,10 @@ def posterize(input: torch.Tensor, bits: Union[int, torch.Tensor]) -> torch.Tensdef sharpness(input: torch.Tensor, factor: Union[float, torch.Tensor]) -> torch.Tensor:- r"""Implements Sharpness function from PIL using torch ops.+ r"""Apply sharpness to the input tensor.++ Implemented Sharpness function from PIL using torch ops. This implementation refers to:+ https://github.com/tensorflow/tpu/blob/master/models/official/efficientnet/autoaugment.py#L326Args:input (torch.Tensor): image tensor with shapes like (C, H, W) or (B, C, H, W) to sharpen.@@ -406,47 +409,72 @@ def sharpness(input: torch.Tensor, factor: Union[float, torch.Tensor]) -> torch.Returns:torch.Tensor: Sharpened image or images.++ Example:+ >>> _ = torch.manual_seed(0)+ >>> sharpness(torch.randn(1, 1, 5, 5), 0.5)+ tensor([[[[-1.1258, -1.1524, -0.2506, -0.4339, 0.8487],+ [ 0.6920, -0.1580, -1.0576, 0.1765, -0.1577],+ [ 1.4437, 0.1998, 0.1799, 0.6588, -0.1435],+ [-0.1116, -0.3068, 0.8381, 1.3477, 0.0537],+ [ 0.6181, -0.4128, -0.8411, -2.3160, -0.1023]]]])"""input = _to_bchw(input)- if isinstance(factor, torch.Tensor):- factor = factor.squeeze()- if len(factor.size()) != 0:- assert input.size(0) == factor.size(0), \- f"Input batch size shall match with factor size if 1d array. Got {input.size(0)} and {factor.size(0)}"- else:- factor = float(factor)+ if not isinstance(factor, torch.Tensor):+ factor = torch.tensor(factor, device=input.device, dtype=input.dtype)++ if len(factor.size()) != 0:+ assert factor.shape == torch.Size([input.size(0)]), (+ "Input batch size shall match with factor size if factor is not a 0-dim tensor. "+ f"Got {input.size(0)} and {factor.shape}")+kernel = torch.tensor([[1, 1, 1],[1, 5, 1],[1, 1, 1]- ], dtype=input.dtype, device=input.device).view(1, 1, 3, 3).repeat(3, 1, 1, 1)+ ], dtype=input.dtype, device=input.device).view(1, 1, 3, 3).repeat(input.size(1), 1, 1, 1) / 13# This shall be equivalent to depthwise conv2d:# Ref: https://discuss.pytorch.org/t/depthwise-and-separable-convolutions-in-pytorch/7315/2degenerate = torch.nn.functional.conv2d(input, kernel, bias=None, stride=1, groups=input.size(1))degenerate = torch.clamp(degenerate, 0., 1.)+ # For the borders of the resulting image, fill in the values of the original image.mask = torch.ones_like(degenerate)padded_mask = torch.nn.functional.pad(mask, [1, 1, 1, 1])padded_degenerate = torch.nn.functional.pad(degenerate, [1, 1, 1, 1])result = torch.where(padded_mask == 1, padded_degenerate, input)- def _blend_one(input1: torch.Tensor, input2: torch.Tensor, factor: Union[float, torch.Tensor]) -> torch.Tensor:- if isinstance(factor, torch.Tensor):- factor = factor.squeeze()- assert len(factor.size()) == 0, f"Factor shall be a float or single element tensor. Got {factor}"- if factor == 0.:- return input1- if factor == 1.:- return input2- diff = (input2 - input1) * factor- res = input1 + diff- if factor > 0. and factor < 1.:- return res- return torch.clamp(res, 0, 1)- if isinstance(factor, (float)) or len(factor.size()) == 0:- return _blend_one(input, result, factor)- return torch.stack([_blend_one(input[i], result[i], factor[i]) for i in range(len(factor))])+ if len(factor.size()) == 0:+ return _blend_one(result, input, factor)+ return torch.stack([_blend_one(result[i], input[i], factor[i]) for i in range(len(factor))])+++def _blend_one(input1: torch.Tensor, input2: torch.Tensor, factor: torch.Tensor) -> torch.Tensor:+ r"""Blend two images into one.++ Args:+ input1 (torch.Tensor): image tensor with shapes like :math:`(H, W)` or :math:`(D, H, W)`.+ input2 (torch.Tensor): image tensor with shapes like :math:`(H, W)` or :math:`(D, H, W)`.+ factor (torch.Tensor): factor 0-dim tensor.++ Returns:+ torch.Tensor: image tensor with the batch in the zero position.+ """+ assert isinstance(input1, torch.Tensor), f"`input1` must be a tensor. Got {input1}."+ assert isinstance(input2, torch.Tensor), f"`input1` must be a tensor. Got {input2}."++ if isinstance(factor, torch.Tensor):+ assert len(factor.size()) == 0, f"Factor shall be a float or single element tensor. Got {factor}."+ if factor == 0.:+ return input1+ if factor == 1.:+ return input2+ diff = (input2 - input1) * factor+ res = input1 + diff+ if factor > 0. and factor < 1.:+ return res+ return torch.clamp(res, 0, 1)# Code taken from: https://github.com/pytorch/vision/pull/796@@ -505,11 +533,13 @@ def _scale_channel(im: torch.Tensor) -> torch.Tensor:def equalize(input: torch.Tensor) -> torch.Tensor:r"""Apply equalize on the input tensor.+Implements Equalize function from PIL using PyTorch ops based on uint8 format:https://github.com/tensorflow/tpu/blob/master/models/official/efficientnet/autoaugment.py#L352Args:input (torch.Tensor): image tensor with shapes like :math:`(C, H, W)` or :math:`(B, C, H, W)` to equalize.+Returns:torch.Tensor: Sharpened image or images."""diff --git a/test/enhance/test_adjust.py b/test/enhance/test_adjust.pyindex 5ef319b11..cbfba3ab5 100644--- a/test/enhance/test_adjust.py+++ b/test/enhance/test_adjust.py@@ -1,7 +1,7 @@import pytestimport kornia-import kornia.testing as utils # test utils+from kornia.testing import tensor_to_gradcheck_var, BaseTesterfrom kornia.constants import piimport torch@@ -52,7 +52,7 @@ class TestAdjustSaturation:def test_gradcheck(self):batch_size, channels, height, width = 2, 3, 4, 5img = torch.rand(batch_size, channels, height, width)- img = utils.tensor_to_gradcheck_var(img) # to var+ img = tensor_to_gradcheck_var(img) # to varassert gradcheck(kornia.adjust_saturation, (img, 2.),raise_exception=True)@@ -123,7 +123,7 @@ class TestAdjustHue:def test_gradcheck(self):batch_size, channels, height, width = 2, 3, 4, 5img = torch.rand(batch_size, channels, height, width)- img = utils.tensor_to_gradcheck_var(img) # to var+ img = tensor_to_gradcheck_var(img) # to varassert gradcheck(kornia.adjust_hue, (img, 2.),raise_exception=True)@@ -255,7 +255,7 @@ class TestAdjustGamma:batch_size, channels, height, width = 2, 3, 4, 5img = torch.ones(batch_size, channels, height, width)img = img.to(device)- img = utils.tensor_to_gradcheck_var(img) # to var+ img = tensor_to_gradcheck_var(img) # to varassert gradcheck(kornia.adjust_gamma, (img, 1., 2.),raise_exception=True)@@ -456,7 +456,7 @@ class TestAdjustContrast:batch_size, channels, height, width = 2, 3, 4, 5img = torch.ones(batch_size, channels, height, width)img = img.to(device)- img = utils.tensor_to_gradcheck_var(img) # to var+ img = tensor_to_gradcheck_var(img) # to varassert gradcheck(kornia.adjust_contrast, (img, 2.),raise_exception=True)@@ -596,7 +596,7 @@ class TestAdjustBrightness:batch_size, channels, height, width = 2, 3, 4, 5img = torch.ones(batch_size, channels, height, width)img = img.to(device)- img = utils.tensor_to_gradcheck_var(img) # to var+ img = tensor_to_gradcheck_var(img) # to varassert gradcheck(kornia.adjust_brightness, (img, 2.),raise_exception=True)@@ -658,7 +658,7 @@ class TestEqualize:bs, channels, height, width = 2, 3, 4, 5inputs = torch.ones(bs, channels, height, width)inputs = inputs.to(device)- inputs = utils.tensor_to_gradcheck_var(inputs)+ inputs = tensor_to_gradcheck_var(inputs)assert gradcheck(kornia.enhance.equalize, (inputs,),raise_exception=True)@@ -727,7 +727,7 @@ class TestEqualize3D:bs, channels, depth, height, width = 2, 3, 6, 4, 5inputs3d = torch.ones(bs, channels, depth, height, width)inputs3d = inputs3d.to(device)- inputs3d = utils.tensor_to_gradcheck_var(inputs3d)+ inputs3d = tensor_to_gradcheck_var(inputs3d)assert gradcheck(kornia.enhance.equalize3d, (inputs3d,),raise_exception=True)@@ -742,3 +742,102 @@ class TestEqualize3D:batch = torch.stack([image3d] * bs)return batch+++class TestSharpness(BaseTester):++ f = kornia.enhance.sharpness++ def test_smoke(self, device, dtype):+ B, C, H, W = 2, 3, 4, 5+ img = torch.rand(B, C, H, W, device=device, dtype=dtype)+ assert isinstance(TestSharpness.f(img, 0.8), torch.Tensor)++ @pytest.mark.parametrize("batch_size, height, width, factor", [+ (1, 4, 5, 0.8), (2, 4, 5, 0.8),+ (1, 4, 5, torch.tensor(0.8)), (2, 4, 5, torch.tensor(0.8)),+ (2, 4, 5, torch.tensor([0.8, 0.7]))])+ @pytest.mark.parametrize("channels", [1, 3, 5])+ def test_cardinality(self, batch_size, channels, height, width, factor, device, dtype):+ inputs = torch.ones(batch_size, channels, height, width, device=device, dtype=dtype)+ assert TestSharpness.f(inputs, factor).shape == torch.Size([batch_size, channels, height, width])++ def test_exception(self, device, dtype):+ img = torch.ones(2, 3, 4, 5, device=device, dtype=dtype)+ with pytest.raises(AssertionError):+ assert TestSharpness.f(img, [0.8, 0.9, 0.6])+ with pytest.raises(AssertionError):+ assert TestSharpness.f(img, torch.tensor([0.8, 0.9, 0.6]))+ with pytest.raises(AssertionError):+ assert TestSharpness.f(img, torch.tensor([0.8]))++ def test_value(self, device, dtype):+ torch.manual_seed(0)++ inputs = torch.rand(1, 3, 3).to(device=device, dtype=dtype)++ # Output generated is similar (1e-2 due to the uint8 conversions) to the below output:+ # img = PIL.Image.fromarray(arr)+ # en = ImageEnhance.Sharpness(img).enhance(0.8)+ # np.array(en) / 255.+ expected = torch.tensor([+ [[[0.4963, 0.7682, 0.0885],+ [0.1320, 0.3305, 0.6341],+ [0.4901, 0.8964, 0.4556]]]], device=device, dtype=dtype)++ # If factor == 1, shall return original+ assert_allclose(TestSharpness.f(inputs, 1), inputs, rtol=1e-4, atol=1e-4)+ assert_allclose(TestSharpness.f(inputs, 0.8), expected, rtol=1e-4, atol=1e-4)++ def test_value_batch(self, device, dtype):+ torch.manual_seed(0)++ inputs = torch.rand(2, 1, 3, 3).to(device=device, dtype=dtype)++ # Output generated is similar (1e-2 due to the uint8 conversions) to the below output:+ # img = PIL.Image.fromarray(arr)+ # en = ImageEnhance.Sharpness(img).enhance(0.8)+ # np.array(en) / 255.+ expected_08 = torch.tensor([+ [[[0.4963, 0.7682, 0.0885],+ [0.1320, 0.3305, 0.6341],+ [0.4901, 0.8964, 0.4556]]],+ [[[0.6323, 0.3489, 0.4017],+ [0.0223, 0.2052, 0.2939],+ [0.5185, 0.6977, 0.8000]]]], device=device, dtype=dtype)+ expected_08_13 = torch.tensor([+ [[[0.4963, 0.7682, 0.0885],+ [0.1320, 0.3305, 0.6341],+ [0.4901, 0.8964, 0.4556]]],+ [[[0.6323, 0.3489, 0.4017],+ [0.0223, 0.1143, 0.2939],+ [0.5185, 0.6977, 0.8000]]]], device=device, dtype=dtype)++ # If factor == 1, shall return original+ assert_allclose(TestSharpness.f(inputs, 1), inputs, rtol=1e-4, atol=1e-4)+ assert_allclose(TestSharpness.f(inputs, torch.tensor([1., 1.])), inputs, rtol=1e-4, atol=1e-4)+ assert_allclose(TestSharpness.f(inputs, 0.8), expected_08, rtol=1e-4, atol=1e-4)+ assert_allclose(TestSharpness.f(inputs, torch.tensor([0.8, 1.3])), expected_08_13, rtol=1e-4, atol=1e-4)++ @pytest.mark.grad+ def test_gradcheck(self, device, dtype):+ bs, channels, height, width = 2, 3, 4, 5+ inputs = torch.rand(bs, channels, height, width, device=device, dtype=dtype)+ inputs = tensor_to_gradcheck_var(inputs)+ assert gradcheck(TestSharpness.f, (inputs, 0.8), raise_exception=True)++ @pytest.mark.skip(reason="union type input")+ @pytest.mark.jit+ def test_jit(self, device, dtype):+ op = torch.jit.script(kornia.enhance.adjust.sharpness)+ inputs = torch.rand(2, 1, 3, 3).to(device=device, dtype=dtype)+ expected = op(input, 0.8)+ actual = op_script(input, 0.8)+ assert_allclose(actual, expected)++ @pytest.mark.skip(reason="Not having it yet.")+ @pytest.mark.nn+ def test_module(self, device, dtype):+ img = torch.ones(2, 3, 4, 4, device=device, dtype=dtype)+ # gray_ops = kornia.enhance.sharpness().to(device, dtype)+ # assert_allclose(gray_ops(img), f(img))