Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(feature): accept an int or NumPy scalar k in CornerHarris (#6506)

Debanjan Sarkarb5651ea01046
diff --git a/changelog.d/6506.fixed.md b/changelog.d/6506.fixed.md
new file mode 100644
index 000000000..94b14202d
--- /dev/null
+++ b/changelog.d/6506.fixed.md
@@ -0,0 +1 @@
+`CornerHarris` accepts an `int` or NumPy scalar `k`, as `harris_response` does, instead of raising a `TypeError` from `register_buffer`: `CornerHarris(0)` now gives the same response as `CornerHarris(0.0)` and `harris_response(input, 0)`. A Python `float` or tensor `k` is stored as before.
diff --git a/kornia/feature/responses.py b/kornia/feature/responses.py
index 79f4cf768..a0ea39855 100644
--- a/kornia/feature/responses.py
+++ b/kornia/feature/responses.py
@@ -15,6 +15,7 @@
# limitations under the License.
#
+import numbers
from typing import Optional, Union
import torch
@@ -430,6 +431,9 @@ class CornerHarris(nn.Module):
super().__init__()
if isinstance(k, float):
self.register_buffer("k", torch.tensor(k))
+ elif isinstance(k, numbers.Real) and not isinstance(k, bool):
+ # An int or a NumPy scalar, which harris_response accepts: register_buffer takes only tensors.
+ self.register_buffer("k", torch.tensor(float(k)))
else:
self.register_buffer("k", k)
self.grads_mode: str = grads_mode
diff --git a/tests/feature/test_responces_local_features.py b/tests/feature/test_responces_local_features.py
index 11b3a8142..a567bdaef 100644
--- a/tests/feature/test_responces_local_features.py
+++ b/tests/feature/test_responces_local_features.py
@@ -17,6 +17,7 @@
import math
+import numpy as np
import pytest
import torch
@@ -62,6 +63,23 @@ class TestCornerHarris(BaseTester):
harris = kornia.feature.CornerHarris(k=0.04).to(device)
assert harris(inp).shape == (2, 6, 4, 4)
+ @pytest.mark.parametrize("k", [0, 1, -1])
+ def test_int_k_6503(self, device, dtype, k):
+ # register_buffer takes only tensors, so an int k raised in __init__, while harris_response accepts it.
+ torch.manual_seed(0)
+ inp = torch.rand(2, 1, 9, 9).to(device=device, dtype=dtype)
+ scores = kornia.feature.CornerHarris(k).to(device)(inp)
+ self.assert_close(scores, kornia.feature.CornerHarris(float(k)).to(device)(inp), rtol=0, atol=0)
+ self.assert_close(scores, kornia.feature.harris_response(inp, k), rtol=0, atol=0)
+
+ @pytest.mark.parametrize("k", [np.int64(0), np.float32(0.0625)])
+ def test_numpy_scalar_k_6503(self, device, dtype, k):
+ # Neither is a Python float, so they reached register_buffer unconverted, like an int.
+ torch.manual_seed(0)
+ inp = torch.rand(2, 1, 9, 9).to(device=device, dtype=dtype)
+ scores = kornia.feature.CornerHarris(k).to(device)(inp)
+ self.assert_close(scores, kornia.feature.harris_response(inp, k), rtol=0, atol=0)
+
def test_corners(self, device, dtype):
inp = torch.tensor(
[