From e7f3917931f531023317eadc343695c3d10cf004 Mon Sep 17 00:00:00 2001 From: Peter Corke Date: Tue, 24 Nov 2026 11:07:35 +1000 Subject: [PATCH] feat: scale, orientation and strength raise for features that do not have them They returned the keypoint size, angle and response whether or not the detector sets them, so Harris features reported an orientation of 0 and a scale of 0. Add a strength flag beside the scale and orientation flags, raise ValueError when a flag is off, and correct the flags: ORB, BRISK and AKAZE do have a scale and an orientation. Slicing, adding and sorting now keep the flags and the image, and the orientation is printed in degrees, not radians with a degree sign. Co-Authored-By: Claude Sonnet 5.5 --- .../ImagePointFeatures.py | 97 ++++++++--- tests/test_image_point_features_extra.py | 161 +++++++++++++++++- 2 files changed, 232 insertions(+), 26 deletions(-) diff --git a/src/machinevisiontoolbox/ImagePointFeatures.py b/src/machinevisiontoolbox/ImagePointFeatures.py index 7ca7dbf5..96db9b28 100644 --- a/src/machinevisiontoolbox/ImagePointFeatures.py +++ b/src/machinevisiontoolbox/ImagePointFeatures.py @@ -5,7 +5,7 @@ import builtins import math from collections.abc import Sequence -from typing import TYPE_CHECKING, Any, Iterator +from typing import TYPE_CHECKING, Any, Iterator, Self import cv2 import matplotlib.lines as mlines @@ -50,6 +50,7 @@ def __init__( scale: bool = False, orient: bool = False, image: np.ndarray | None = None, + strength: bool = True, ) -> None: """ Create set of 2D point features @@ -62,6 +63,12 @@ def __init__( :type scale: bool, optional :param orient: features have an inherent orientation, defaults to False :type orient: bool, optional + :param strength: features have a strength (detector response), defaults to True + :type strength: bool, optional + + The :attr:`scale`, :attr:`orientation` and :attr:`strength` properties raise + ``ValueError`` for a set of features that does not have that quantity, for example + :attr:`orientation` of FAST features. A :class:`~machinevisiontoolbox.ImagePointFeatures.BaseFeature2D` object: @@ -82,6 +89,7 @@ def __init__( self._has_scale: bool = scale self._has_orient: bool = orient + self._has_strength: bool = strength self._image: Any = image self._feature_type: str | None = None if kp is None: @@ -90,6 +98,27 @@ def __init__( self._kp = list(kp) self._descriptor: np.ndarray | None = des + def _require(self, flag: bool, what: str) -> None: + """Raise ValueError if these features do not have ``what``""" + if not flag: + kind = self._feature_type or self.__class__.__name__ + raise ValueError(f"{kind} features have no {what}") + + def _like(self) -> Self: + """A new empty set of the same kind, with the metadata of this one + + The flags that say which of scale, orientation and strength the features + have, the feature type and the image they came from are copied, so a set made + by slicing, adding or sorting keeps them. + """ + new = self.__class__() + new._has_scale = self._has_scale + new._has_orient = self._has_orient + new._has_strength = self._has_strength + new._feature_type = self._feature_type + new._image = self._image + return new + def __len__(self) -> int: """ Number of features (base method) @@ -136,9 +165,7 @@ def __getitem__( :seealso: :meth:`.__len__` """ - new = self.__class__() # Get item from point feature object (base method) - new._has_scale = self._has_scale - new._has_orient = self._has_orient + new = self._like() # Get item from point feature object (base method) # compute canonical integer index list for both _kp and descriptor n = len(self) if isinstance(i, int): @@ -190,14 +217,13 @@ def __str__(self) -> str: if len(self) > 1: # String representation of feature (base method) return f"{self.__class__.__name__} features, {len(self)} points" else: - s = ( - f"{self.__class__.__name__}: ({self.u:.1f}, {self.v:.1f})," - f" strength={self.strength:.2f}" - ) + s = f"{self.__class__.__name__}: ({self.u:.1f}, {self.v:.1f})," + if self._has_strength: + s += f" strength={self.strength:.2f}" if self._has_scale: s += f", scale={self.scale:.1f}" if self._has_orient: - s += f", orient={self.orientation:.1f}°" + s += f", orient={np.degrees(self.orientation):.1f}°" s += f", id={self.id}" return s @@ -225,14 +251,13 @@ def list(self) -> None: :seealso: :meth:`table` """ for i, f in enumerate(self): # List matches - s = ( - f"{self._feature_type} feature {i}: ({f.u:.1f}, {f.v:.1f})," - f" strength={f.strength:.2f}" - ) + s = f"{self._feature_type} feature {i}: ({f.u:.1f}, {f.v:.1f})," + if f._has_strength: + s += f" strength={f.strength:.2f}" if f._has_scale: s += f", scale={f.scale:.1f}" if f._has_orient: - s += f", orient={f.orientation:.1f}°" + s += f", orient={np.degrees(f.orientation):.1f}°" s += f", id={f.id}" print(s) @@ -248,8 +273,9 @@ def table(self) -> None: columns = [ Column("#"), Column("centroid"), - Column("strength", fmt="{:.3g}"), ] # Print features in tabular form + if self._has_strength: + columns.append(Column("strength", fmt="{:.3g}")) if self._has_scale: columns.append(Column("scale", fmt="{:.3g}")) if self._has_orient: @@ -257,11 +283,13 @@ def table(self) -> None: columns.append(Column("id", fmt="{:d}")) table = ANSITable(*columns, border="thin") for i, f in enumerate(self): - values = [f.strength] + values = [] + if self._has_strength: + values.append(f.strength) if self._has_scale: values.append(f.scale) if self._has_orient: - values.append(f.orientation) + values.append(np.degrees(f.orientation)) table.row(i, f"{f.u:.1f}, {f.v:.1f}", *values, f.id) table.print() @@ -361,8 +389,7 @@ def __add__(self, other: "BaseFeature2D | builtins.list | None") -> "BaseFeature self._feature_type, other._feature_type, ) - new = self.__class__() - new._feature_type = self._feature_type + new = self._like() new._kp = self._kp + other._kp if self._descriptor is not None and other._descriptor is not None: new._descriptor = np.vstack((self._descriptor, other._descriptor)) @@ -496,6 +523,12 @@ def orientation(self) -> "builtins.list[float]": # Orientation of feature :return: Orientation in radians :rtype: float or list of float + :raises ValueError: if the features have no orientation, such as FAST or Harris + features + + .. versionchanged:: 2.5.0 + Raises ``ValueError`` if the features have no orientation. It used to return + a constant for a detector that has no orientation. Example: @@ -507,7 +540,7 @@ def orientation(self) -> "builtins.list[float]": # Orientation of feature >>> orb[0].orientation >>> orb[:5].orientation """ - # TODO should be in radians + self._require(self._has_orient, "orientation") return [np.radians(kp.angle) for kp in self._kp] @property @@ -518,6 +551,11 @@ def scale(self) -> "builtins.list[float]": # Scale of feature :return: Scale :rtype: float or list of float + :raises ValueError: if the features have no scale, such as FAST or Harris features + + .. versionchanged:: 2.5.0 + Raises ``ValueError`` if the features have no scale. It used to return the + keypoint size, which is a constant for a detector that has no scale. Example: @@ -529,6 +567,7 @@ def scale(self) -> "builtins.list[float]": # Scale of feature >>> orb[0].scale >>> orb[:5].scale """ + self._require(self._has_scale, "scale") return [kp.size for kp in self._kp] @property @@ -539,6 +578,10 @@ def strength(self) -> "builtins.list[float]": # Strength of feature :return: Strength :rtype: float or list of float + :raises ValueError: if the features have no strength + + .. versionchanged:: 2.5.0 + Raises ``ValueError`` if the features have no strength. Example: @@ -550,6 +593,7 @@ def strength(self) -> "builtins.list[float]": # Strength of feature >>> orb[0].strength >>> orb[:5].strength """ + self._require(self._has_strength, "strength") return [kp.response for kp in self._kp] @property @@ -906,11 +950,10 @@ def sort( if self._descriptor is not None: self._descriptor = np.take(self._descriptor, sorted_index, axis=0) else: - new = self.__class__() + new = self._like() new._kp = [self._kp[i] for i in sorted_index] if self._descriptor is not None: new._descriptor = np.take(self._descriptor, sorted_index, axis=0) - new._feature_type = self._feature_type return new return None @@ -2416,7 +2459,11 @@ def ORB(self, scoreType: str = "harris", **kwargs: Any) -> "ORBFeature": scoreoptions = {"harris": cv2.ORB_HARRIS_SCORE, "fast": cv2.ORB_FAST_SCORE} return self._image2feature( - ORBFeature, scoreType=scoreoptions[scoreType], **kwargs + ORBFeature, + scale=True, + orient=True, + scoreType=scoreoptions[scoreType], + **kwargs, ) def BRISK(self, **kwargs: Any) -> "BRISKFeature": @@ -2452,7 +2499,7 @@ def BRISK(self, **kwargs: Any) -> "BRISKFeature": :seealso: :class:`BRISKFeature` `cv2.BRISK_create `_ """ - return self._image2feature(BRISKFeature, **kwargs) + return self._image2feature(BRISKFeature, scale=True, orient=True, **kwargs) def AKAZE(self, **kwargs: Any) -> "AKAZEFeature": """ @@ -2488,7 +2535,7 @@ def AKAZE(self, **kwargs: Any) -> "AKAZEFeature": :class:`~machinevisiontoolbox.ImagePointFeatures.AKAZEFeature` `cv2.AKAZE `_ """ - return self._image2feature(AKAZEFeature, **kwargs) + return self._image2feature(AKAZEFeature, scale=True, orient=True, **kwargs) def Harris(self, **kwargs: Any) -> "HarrisFeature": r""" diff --git a/tests/test_image_point_features_extra.py b/tests/test_image_point_features_extra.py index f77269f3..5567b370 100644 --- a/tests/test_image_point_features_extra.py +++ b/tests/test_image_point_features_extra.py @@ -146,7 +146,8 @@ def test_several(self): def test_one_with_scale_and_orientation(self): s = str(make_features(3)[1]) assert s.startswith("SIFTFeature: (20.0, 25.0), strength=0.20") - assert "scale=3.0" in s and "orient=0.5°" in s and s.endswith("id=1") + # the orientation is 30 degrees; it was printed as radians (0.5) with a degree sign + assert "scale=3.0" in s and "orient=30.0°" in s and s.endswith("id=1") def test_one_without_scale_and_orientation(self): f = make_features(3)[1] @@ -166,6 +167,21 @@ def test_table(self, capsys): assert "strength" in out and "scale" in out and "orient" in out assert "20.0, 25.0" in out + def test_table_and_list_show_the_orientation_in_degrees(self, capsys): + make_features(3).table() + assert "30°" in capsys.readouterr().out # feature 1 is at 30 degrees + make_features(3).list() + assert "orient=30.0°" in capsys.readouterr().out + + def test_without_strength(self, capsys): + f = make_features(3) + f._has_strength = False + assert "strength" not in str(f[1]) + f.table() + assert "strength" not in capsys.readouterr().out + f.list() + assert "strength" not in capsys.readouterr().out + def test_table_without_scale_and_orientation(self, capsys): f = make_features(3) f._has_scale = f._has_orient = False @@ -971,3 +987,146 @@ def test_estimator(self, matches, name, kwargs, n_returned, has_mask): else: with pytest.raises(ValueError, match="not been set"): matches.inliers + + +# --------------------------------------------------------------------------- # +# scale, orientation and strength exist only for the features that have them + + +class TestPropertiesThatMayBeAbsent: + @staticmethod + def features(scale, orient, strength=True): + f = make_features(3) + f._has_scale, f._has_orient, f._has_strength = scale, orient, strength + f._feature_type = "FAST" + return f + + @pytest.mark.parametrize( + "name, message", + [ + ("scale", "FAST features have no scale"), + ("orientation", "FAST features have no orientation"), + ("strength", "FAST features have no strength"), + ], + ) + def test_raise_if_the_features_do_not_have_it(self, name, message): + f = self.features(False, False, False) + with pytest.raises(ValueError, match=message): + getattr(f, name) + with pytest.raises(ValueError, match=message): + getattr(f[1], name) # a single feature too + + def test_return_values_if_the_features_have_them(self): + f = self.features(True, True, True) + nt.assert_allclose(f.scale, [2, 3, 4]) + nt.assert_allclose(f.orientation, np.radians([0, 30, 60])) + nt.assert_allclose(f.strength, [0.1, 0.2, 0.3]) + + def test_each_is_independent_of_the_others(self): + f = self.features(True, False) + assert len(f.scale) == 3 and len(f.strength) == 3 + with pytest.raises(ValueError, match="orientation"): + f.orientation + + def test_sort_and_filter_by_a_missing_quantity_raise(self): + f = self.features(False, False) + with pytest.raises(ValueError, match="no scale"): + f.sort("scale") + with pytest.raises(ValueError, match="no scale"): + f.filter(minscale=1) + f.sort("strength") # the one it has still works + f.filter(minstrength=0.15) + + def test_drawing_circles_needs_a_scale_and_a_hand_needs_an_orientation(self): + f = self.features(False, False) + f.plot() # markers only: nothing needed + with pytest.raises(ValueError, match="no scale"): + f.plot(filled=True) + g = self.features(True, False) + g.plot(filled=True) + with pytest.raises(ValueError, match="no orientation"): + g.plot(filled=True, hand=True) + self.features(True, True).plot(filled=True, hand=True) + + def test_flags_are_kept_by_slicing_adding_and_sorting(self): + img = Image(np.zeros((50, 50), dtype=np.uint8)) + f = self.features(True, False, True) + f._image = img + for g in ( + f[1:], + f[[0, 2]], + f[np.array([True, False, True])], + f + f, + f.sort("scale"), + f.subset(2), + ): + assert (g._has_scale, g._has_orient, g._has_strength) == (True, False, True) + assert g._feature_type == "FAST" + assert g._image is img + assert len(f + f) == 6 + + +# the algorithms the toolbox has, and what each really provides: the flags must agree +# with the keypoints, or the properties would raise for good data, or return junk +ALGORITHMS = [ + # name, has scale, has orientation + ("SIFT", True, True), + ("ORB", True, True), + ("BRISK", True, True), + ("AKAZE", True, True), + ("Harris", False, False), +] + + +class TestFlagsAgreeWithTheData: + @pytest.fixture + def image(self): + return Image.Read("eiffel-1.png", mono=True) + + @pytest.mark.parametrize("name, has_scale, has_orient", ALGORITHMS) + def test_algorithm(self, image, name, has_scale, has_orient): + f = getattr(image, name)() + assert len(f) > 50 + assert (f._has_scale, f._has_orient, f._has_strength) == ( + has_scale, + has_orient, + True, + ) + sizes = np.array([kp.size for kp in f._kp]) + angles = np.array([kp.angle for kp in f._kp]) + + # strength is always there, and not all the same + assert np.ptp(f.strength) > 0 + + if has_scale: + assert sizes.min() > 0 and np.ptp(sizes) > 0 # varies, so it is real + assert len(f.scale) == len(f) + else: + assert np.ptp(sizes) == 0 # a constant, so it is not a scale + with pytest.raises(ValueError, match="no scale"): + f.scale + + if has_orient: + assert np.ptp(angles) > 90 # spread round the circle, so it is real + assert np.all(np.abs(f.orientation) <= 2 * np.pi) + else: + assert np.ptp(angles) == 0 + with pytest.raises(ValueError, match="no orientation"): + f.orientation + + @pytest.mark.parametrize("name, has_scale, has_orient", ALGORITHMS) + def test_a_sum_and_a_slice_keep_what_the_algorithm_has( + self, image, name, has_scale, has_orient + ): + f = getattr(image, name)() + for g in (f[:20], f[:20] + f[20:40], f.sort(inplace=False)): + assert (g._has_scale, g._has_orient) == (has_scale, has_orient) + assert g._image is not None or g is f + + def test_printing_an_orb_feature_shows_scale_and_orientation_in_degrees( + self, image + ): + s = str(image.ORB()[0]) + assert "scale=" in s and "orient=" in s + degrees = float(s.split("orient=")[1].split("°")[0]) + assert 0 <= degrees < 360