diff --git a/src/machinevisiontoolbox/ImagePointFeatures.py b/src/machinevisiontoolbox/ImagePointFeatures.py index 56fabb19..62e0963e 100644 --- a/src/machinevisiontoolbox/ImagePointFeatures.py +++ b/src/machinevisiontoolbox/ImagePointFeatures.py @@ -92,6 +92,7 @@ def __init__( self._has_strength: bool = strength self._image: Any = image self._feature_type: str | None = None + self._detector: str | None = None if kp is None: self._kp: list[cv2.KeyPoint] = [] else: @@ -116,9 +117,24 @@ def _like(self) -> Self: new._has_orient = self._has_orient new._has_strength = self._has_strength new._feature_type = self._feature_type + new._detector = self._detector new._image = self._image return new + @property + def _label(self) -> str: + """Name of the algorithm that makes these features, for display + + A feature is a detected keypoint and its descriptor. Most algorithms, such + as SIFT, provide both, so are named for the algorithm. For a detector joined + to a different descriptor by :meth:`Image.ComboFeature` it is + ``"detector+descriptor"``, for example ``"FAST+BRIEF"``. + """ + name = self._feature_type or self.__class__.__name__.removesuffix("Feature") + if self._detector is not None and self._detector != name: + name = f"{self._detector}+{name}" + return name + def __len__(self) -> int: """ Number of features (base method) @@ -200,9 +216,12 @@ def __str__(self) -> str: :return: string representation :rtype: str - For a feature object of length one display the feature type, position, + For a feature object of length one display the algorithm, position, strength and id. For a feature object with multiple features display - the feature type and number of features. + the algorithm and number of features. A feature is a detected keypoint with + its descriptor. The algorithm is named once if it provides both, for + example SIFT, and as ``"detector+descriptor"`` if they are different, for + example FAST+BRIEF, made by :meth:`Image.ComboFeature`. Example: @@ -215,9 +234,9 @@ def __str__(self) -> str: >>> orb[0] # feature 0 """ if len(self) > 1: # String representation of feature (base method) - return f"{self.__class__.__name__} features, {len(self)} points" + return f"{self._label} features, {len(self)} points" else: - s = f"{self.__class__.__name__}: ({self.u:.1f}, {self.v:.1f})," + s = f"{self._label} feature: ({self.u:.1f}, {self.v:.1f})," if self._has_strength: s += f" strength={self.strength:.2f}" if self._has_scale: @@ -251,7 +270,7 @@ 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})," + s = f"{self._label} feature {i}: ({f.u:.1f}, {f.v:.1f})," if f._has_strength: s += f" strength={f.strength:.2f}" if f._has_scale: @@ -777,7 +796,8 @@ def match( :type metric: str, optional :param sort: sort features by strength, defaults to True :type sort: bool, optional - :raises ValueError: bad metric name provided + :raises ValueError: bad metric name provided, or the two sets have different + kinds of descriptor, for example SIFT and ORB :return: set of candidate matches :rtype: :class:`FeatureMatch` instance @@ -820,6 +840,12 @@ def match( des2 = other.descriptor if des1 is None or des2 is None: raise ValueError("features have no descriptors") + if des1.dtype != des2.dtype or des1.shape[1] != des2.shape[1]: + raise ValueError( + "cannot match features with different kinds of descriptor: " + f"{self._feature_type} ({des1.shape[1]} {des1.dtype}) and " + f"{other._feature_type} ({des2.shape[1]} {des2.dtype})" + ) if metric is None: metric = "hamming" if des1.dtype == np.uint8 else "L2" @@ -908,6 +934,7 @@ def subset(self, N: int = 100) -> "BaseFeature2D": k = k[:N] new = self[k] new._feature_type = self._feature_type + new._detector = self._detector return new def sort( @@ -2280,6 +2307,23 @@ def _SURF_create(**kwargs: Any) -> Any: # ------------------------------------------------------------------------- +def _set_keypoint_ids(kp: list, image: Any, id: str | int) -> None: + """Set the ``class_id`` of each keypoint, as the ``id`` argument of the features says""" + if id == "image": + if image.id is not None: + # copy image id into the keypoints + for k in kp: + k.class_id = image.id + elif id == "index": + for i, k in enumerate(kp): + k.class_id = i + elif isinstance(id, int): + for k in kp: + k.class_id = id + else: + raise ValueError(f"id must be 'image', 'index' or an int, got {id!r}") + + class ImagePointFeaturesMixin(ImageMixinBase): """ Methods of :class:`Image` that find point features, such as SIFT, ORB and Harris @@ -2312,19 +2356,7 @@ def _image2feature( # kp is a list of N KeyPoint objects # des is NxM ndarray of keypoint descriptors - if id == "image": - if image.id is not None: - # copy image id into the keypoints - for k in kp: - k.class_id = image.id - elif id == "index": - for i, k in enumerate(kp): - k.class_id = i - elif isinstance(id, int): - for k in kp: - k.class_id = id - else: - raise ValueError(f"id must be 'image', 'index' or an int, got {id!r}") + _set_keypoint_ids(kp, image, id) # do sorting in here @@ -2583,62 +2615,231 @@ def Harris(self, **kwargs: Any) -> "HarrisFeature": def ComboFeature( self, - detector: Any, - descriptor: Any, - det_opts: dict[str, Any], - des_opts: dict[str, Any], + detector: str, + descriptor: str, + det_opts: dict[str, Any] | None = None, + des_opts: dict[str, Any] | None = None, + nfeat: int | None = None, + id: str | int = "image", ) -> BaseFeature2D: """ - Combination feature detector and descriptor - - :param detector: detector name - :type detector: str - :param descriptor: descriptor name - :type descriptor: str - :param det_opts: options for detector - :type det_opts: dict - :param des_opts: options for descriptor + Find features using one algorithm to detect and another to describe + + :param detector: name of the detector, one of ``"FAST"``, ``"AGAST"``, + ``"GFTT"``, ``"Harris"``, ``"SIFT"``, ``"ORB"``, ``"BRISK"`` or + ``"AKAZE"`` + :param descriptor: name of the descriptor, one of ``"SIFT"``, ``"ORB"``, + ``"BRISK"``, ``"AKAZE"``, ``"FREAK"``, ``"BRIEF"``, ``"DAISY"``, + ``"LATCH"``, ``"LUCID"`` or ``"BOOST"`` + :param det_opts: options passed to the detector, defaults to None + :param des_opts: options passed to the descriptor, defaults to None + :param nfeat: keep at most this many of the strongest keypoints, defaults to + None, which keeps all of them. A few can be lost, because a descriptor + needs a margin of image around a keypoint + :param id: what to put in each keypoint's ``id``: ``"image"`` (the image id), + ``"index"`` (0, 1, ...) or an int, defaults to ``"image"`` + :raises ValueError: unknown detector or descriptor, a pair that cannot be + combined, or a descriptor that needs a color image given a greyscale one :return: set of 2D point features :rtype: :class:`BaseFeature2D` subclass - Detect corner features using the specified detector ``detector`` and - describe them using the specified descriptor ``descriptor``. A large - number of possible combinations are possible. + Detect keypoints with ``detector`` and describe each one with ``descriptor``. + Most detectors, such as FAST, find corners but give no description of them, + and most descriptors, such as BRIEF, describe the image around a keypoint + but do not find one. This method joins any detector to almost any + descriptor. There are 8 detectors and 10 descriptors, which is + 73 combinations that work out of 80: + + +------------+-----------------------------------------------------------+ + | descriptor | detector | + | +------+-------+------+--------+------+-----+-------+-------+ + | | FAST | AGAST | GFTT | Harris | SIFT | ORB | BRISK | AKAZE | + +============+======+=======+======+========+======+=====+=======+=======+ + | **SIFT** | ✓ | ✓ | ✓ | ✓ | ✔ | ✓ | ✓ | ✓ | + +------------+------+-------+------+--------+------+-----+-------+-------+ + | **ORB** | ✓ | ✓ | ✓ | ✓ | 1 | ✔ | ✓ | ✓ | + +------------+------+-------+------+--------+------+-----+-------+-------+ + | **BRISK** | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✔ | ✓ | + +------------+------+-------+------+--------+------+-----+-------+-------+ + | **AKAZE** | | | | | | | | ✔ | + +------------+------+-------+------+--------+------+-----+-------+-------+ + | **FREAK** | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | + +------------+------+-------+------+--------+------+-----+-------+-------+ + | **BRIEF** | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | + +------------+------+-------+------+--------+------+-----+-------+-------+ + | **DAISY** | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | + +------------+------+-------+------+--------+------+-----+-------+-------+ + | **LATCH** | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | + +------------+------+-------+------+--------+------+-----+-------+-------+ + | **LUCID** | 2 | 2 | 2 | 2 | 2 | 2 | 2 | 2 | + +------------+------+-------+------+--------+------+-----+-------+-------+ + | **BOOST** | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | + +------------+------+-------+------+--------+------+-----+-------+-------+ + + The columns are the detectors and the rows are the descriptors. In the table, + + - ``✓`` is a combination that works + - ``✔`` is a combination that works, and is an algorithm that defines both a + detector and a descriptor, for example SIFT + - an empty cell is a combination that cannot be made. The AKAZE descriptor + uses information that only the AKAZE detector records in its keypoints, + so it cannot be used with another detector. + + 1. The ORB descriptor reads a pyramid level from each keypoint, which the + SIFT detector uses for something else. For SIFT keypoints it is set to + the full resolution image, so the ORB descriptor ignores their scale and + has no scale invariance. + 2. The LUCID descriptor describes a color patch, so it needs a color image. + + A set of features can also provide the scale, orientation and strength (the + detector's response) of each keypoint. This depends on the detector, as in + this table, where ✓ means that it does: + + +-----------------+-----------------------------------------------------------+ + | provides | detector | + | +------+-------+------+--------+------+-----+-------+-------+ + | | FAST | AGAST | GFTT | Harris | SIFT | ORB | BRISK | AKAZE | + +=================+======+=======+======+========+======+=====+=======+=======+ + | **position** | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | + +-----------------+------+-------+------+--------+------+-----+-------+-------+ + | **scale** | | | | | ✓ | ✓ | ✓ | ✓ | + +-----------------+------+-------+------+--------+------+-----+-------+-------+ + | **orientation** | 3 | 3 | 3 | 3 | ✓ | ✓ | ✓ | ✓ | + +-----------------+------+-------+------+--------+------+-----+-------+-------+ + | **strength** | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | + +-----------------+------+-------+------+--------+------+-----+-------+-------+ + + 3. The detector does not provide orientation, but the BRISK and FREAK + descriptors compute orientation internally. + + The result is a set of the class of the descriptor, for example + :class:`BRIEFFeature`, and can be matched with another set made with the + same descriptor. The detector can differ, and the descriptors of the two + sets must be of the same kind. + + .. rubric:: Examples - .. warning:: Incomplete - - :seealso: :class:`BOOSTFeature` :class:`BRIEFFeature` :class:`DAISYFeature` :class:`FREAKFeature` :class:`LATCHFeature` :class:`LUCIDFeature` - """ + .. runblock:: pycon - # WORK IN PROGRESS + >>> from machinevisiontoolbox import Image + >>> img = Image.Read("eiffel-1.png") + >>> features = img.ComboFeature("FAST", "BRIEF", nfeat=500) + >>> print(features) + >>> len(features) + >>> features.descriptor.shape + + .. rubric:: References + + - Comparison of the detectors and descriptors: Performance analysis of + keypoint detectors and binary descriptors under varying degrees of + photometric and geometric transformations. + Shuvo Kumar Paul, Pourya Hoseini, Mircea Nicolescu and Monica Nicolescu. + `arXiv:2012.04135 `_, 2020. + - AGAST: Adaptive and generic corner detection based on the accelerated + segment test. + Elmar Mair, Gregory D. Hager, Darius Burschka, Michael Suppa and + Gerhard Hirzinger. + In European Conference on Computer Vision (ECCV), 2010. + - AKAZE: Fast explicit diffusion for accelerated features in nonlinear + scale spaces. + Pablo F. Alcantarilla, Jesús Nuevo and Adrien Bartoli. + IEEE Trans. Pattern Anal. Machine Intell., 34(7):1281–1298, 2011. + - BOOST: Boosting binary keypoint descriptors. + Tomasz Trzcinski, Mario Christoudias, Vincent Lepetit and Pascal Fua. + In Computer Vision and Pattern Recognition (CVPR), 2013. Also: + Learning image descriptors with boosting. + Tomasz Trzcinski, Mario Christoudias and Vincent Lepetit. + IEEE Trans. Pattern Anal. Machine Intell., 2013. + - BRIEF: Binary robust independent elementary features. + Michael Calonder, Vincent Lepetit, Christoph Strecha and Pascal Fua. + In European Conference on Computer Vision (ECCV), pages 778–792, 2010. + - BRISK: Binary robust invariant scalable keypoints. + Stefan Leutenegger, Margarita Chli and Roland Yves Siegwart. + In International Conference on Computer Vision (ICCV), pages 2548–2555, + 2011. + - DAISY: An efficient dense descriptor applied to wide baseline stereo. + Engin Tola, Vincent Lepetit and Pascal Fua. + IEEE Trans. Pattern Anal. Machine Intell., 32(5):815–830, May 2010. + - FAST: Machine learning for high-speed corner detection. + Edward Rosten and Tom Drummond. + In European Conference on Computer Vision (ECCV), pages 430–443, 2006. + - FREAK: Fast retina keypoint. + Alexandre Alahi, Raphael Ortiz and Pierre Vandergheynst. + In Computer Vision and Pattern Recognition (CVPR), pages 510–517, 2012. + - GFTT: Good features to track. + Jianbo Shi and Carlo Tomasi. + In Computer Vision and Pattern Recognition (CVPR), pages 593–600, 1994. + - Harris: A combined corner and edge detector. + CG Harris and MJ Stephens. + Proceedings of the Fourth Alvey Vision Conference, Manchester, + pages 147–151, 1988. + - LATCH: Learned arrangements of three patch codes. + Gil Levi and Tal Hassner. + `arXiv:1501.03719 `_, 2015. + - LUCID: Locally uniform comparison image descriptor. + Andrew Ziegler, Eric Christiansen, David Kriegman and Serge J. Belongie. + In Advances in Neural Information Processing Systems (NIPS), 2012. + - ORB: An efficient alternative to SIFT or SURF. + Ethan Rublee, Vincent Rabaud, Kurt Konolige and Gary Bradski. + In International Conference on Computer Vision (ICCV), pages 2564–2571, + 2011. + - SIFT: Distinctive image features from scale-invariant keypoints. + David G. Lowe. + Int. J. Comput. Vision, 60(2):91–110, November 2004. - detectors: dict[str, Any] = { - "AGAST": getattr(cv2, "AgastFeatureDetector_create"), - "FAST": getattr(cv2, "FastFeatureDetector_create"), - "GoodFeaturesToTrack": getattr(cv2, "GFTTDetector_create"), - } + .. versionadded:: 2.5.0 - descriptors = { - "BOOST": (cv2.xfeatures2d.BoostDesc_create, BOOSTFeature), # type: ignore[attr-defined] - "BRIEF": (cv2.xfeatures2d.BriefDescriptorExtractor_create, BRIEFFeature), # type: ignore[attr-defined] - "DAISY": (cv2.xfeatures2d.BriefDescriptorExtractor_create, DAISYFeature), # type: ignore[attr-defined] - "FREAK": (cv2.xfeatures2d.BriefDescriptorExtractor_create, FREAKFeature), # type: ignore[attr-defined] - "LATCH": (cv2.xfeatures2d.BriefDescriptorExtractor_create, LATCHFeature), # type: ignore[attr-defined] - "LUCID": (cv2.xfeatures2d.BriefDescriptorExtractor_create, LUCIDFeature), # type: ignore[attr-defined] - } - # eg. Feature2D('FAST', 'FREAK') - if detector in detectors: - # call it - kp = detectors[detector](self._A, **det_opts) - elif callable(detector): - # call it - kp = detector(self._A, **det_opts) - else: + .. seealso:: :class:`BOOSTFeature` :class:`BRIEFFeature` :class:`DAISYFeature` :class:`FREAKFeature` :class:`LATCHFeature` :class:`LUCIDFeature` + """ + try: + det_factory, has_scale, has_orient = _COMBO_DETECTORS[detector] + except KeyError: raise ValueError( - f"detector must be a callable or one of {list(detectors)}, got {detector!r}" + f"unknown detector {detector!r}, must be one of " + f"{', '.join(_COMBO_DETECTORS)}" + ) from None + try: + des_factory, cls, needs_color, finds_orient = _DESCRIPTORS[descriptor] + except KeyError: + raise ValueError( + f"unknown descriptor {descriptor!r}, must be one of " + f"{', '.join(_DESCRIPTORS)}" + ) from None + reason = _unsupported_pair(detector, descriptor) + if reason is not None: + raise ValueError(f"cannot combine {detector} with {descriptor}: {reason}") + if needs_color and self.nplanes != 3: + raise ValueError( + f"{descriptor} describes a color patch, so needs a color image" ) - raise NotImplementedError("ComboFeature is a work in progress") + mono = self.mono() + kp = list(det_factory(**(det_opts or {})).detect(mono._A, None)) + if nfeat is not None: + kp = sorted(kp, key=lambda k: k.response, reverse=True)[:nfeat] + + if detector == "SIFT" and descriptor == "ORB": + # SIFT packs its scale space level and layer into the keypoint's octave, + # and ORB reads it as its own pyramid level, which fails. Describing + # at full resolution is the only sensible reading + kp = [ + cv2.KeyPoint(k.pt[0], k.pt[1], k.size, k.angle, k.response, 0, -1) + for k in kp + ] + + # the descriptor may drop keypoints too close to the edge + kp, des = des_factory(**(des_opts or {})).compute( + self._A if needs_color else mono._A, kp + ) + + # after description, since the AKAZE descriptor uses class_id + _set_keypoint_ids(kp, mono, id) + + features = cls(kp, des, scale=has_scale, orient=has_orient or finds_orient) + features._feature_type = descriptor + features._detector = detector + features._image = self + return features class _Harris_create: @@ -2657,6 +2858,11 @@ def __init__( self.patch = patch self.scale = None + def detect( + self, image: np.ndarray, mask: np.ndarray | None = None + ) -> list[cv2.KeyPoint]: + return self.detectAndCompute(image, mask)[0] + def detectAndCompute( self, image: np.ndarray, mask: np.ndarray | None = None ) -> tuple[list[cv2.KeyPoint], np.ndarray]: @@ -2727,3 +2933,65 @@ def detectAndCompute( "AKAZE": (lambda **kw: _resolve_feature_create("AKAZE")(**kw), True, True), "Harris": (_Harris_create, False, False), } + + +def _contrib_create(name: str) -> Any: + """A factory for an OpenCV algorithm that lives in the contrib modules in OpenCV 5""" + + def create(**kwargs: Any) -> Any: + try: + return _resolve_feature_create(name)(**kwargs) + except AttributeError: + raise RuntimeError( + f"{name} is not available in this OpenCV, which needs its contrib " + "modules: pip install opencv-contrib-python" + ) from None + + return create + + +# Detectors that Image.ComboFeature can join to a descriptor, each of which has a +# ``detect`` method, with what the keypoints it finds provide. +# +# name: (factory, has scale, has orientation) +_COMBO_DETECTORS: dict[str, tuple[Any, bool, bool]] = { + "FAST": ( + lambda **kw: getattr(cv2, "FastFeatureDetector_create")(**kw), + False, + False, + ), + "AGAST": (_contrib_create("AgastFeatureDetector"), False, False), + "GFTT": (lambda **kw: getattr(cv2, "GFTTDetector_create")(**kw), False, False), + "Harris": (_Harris_create, False, False), + "SIFT": _DETECTORS["SIFT"], + "ORB": _DETECTORS["ORB"], + "BRISK": _DETECTORS["BRISK"], + "AKAZE": _DETECTORS["AKAZE"], +} + +# Descriptors that Image.ComboFeature can join to a detector, each of which has a +# ``compute`` method. +# +# name: (factory, class of the result, needs a color image, finds an orientation) +_DESCRIPTORS: dict[str, tuple[Any, type[BaseFeature2D], bool, bool]] = { + "SIFT": (_DETECTORS["SIFT"][0], SIFTFeature, False, False), + "ORB": (_DETECTORS["ORB"][0], ORBFeature, False, False), + "BRISK": (_DETECTORS["BRISK"][0], BRISKFeature, False, True), + "AKAZE": (_DETECTORS["AKAZE"][0], AKAZEFeature, False, False), + "FREAK": (_contrib_create("FREAK"), FREAKFeature, False, True), + "BRIEF": (_contrib_create("BriefDescriptorExtractor"), BRIEFFeature, False, False), + "DAISY": (_contrib_create("DAISY"), DAISYFeature, False, False), + "LATCH": (_contrib_create("LATCH"), LATCHFeature, False, False), + "LUCID": (_contrib_create("LUCID"), LUCIDFeature, True, False), + "BOOST": (_contrib_create("BoostDesc"), BOOSTFeature, False, False), +} + + +def _unsupported_pair(detector: str, descriptor: str) -> str | None: + """Why this detector cannot be joined to this descriptor, or None if it can""" + if descriptor == "AKAZE" and detector != "AKAZE": + return ( + "the AKAZE descriptor needs the scale space index that only the AKAZE " + "detector records" + ) + return None diff --git a/tests/test_combofeature.py b/tests/test_combofeature.py new file mode 100644 index 00000000..d8bc9e86 --- /dev/null +++ b/tests/test_combofeature.py @@ -0,0 +1,151 @@ +#!/usr/bin/env python + +import unittest + +import numpy as np + +from machinevisiontoolbox import Image +from machinevisiontoolbox.ImagePointFeatures import ( + _COMBO_DETECTORS, + _DESCRIPTORS, + BRIEFFeature, + FREAKFeature, + LUCIDFeature, + _unsupported_pair, +) + + +class TestComboFeature(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.img = Image.Read("eiffel-1.png") + + def test_every_supported_pair_works(self): + for det in _COMBO_DETECTORS: + for des in _DESCRIPTORS: + if _unsupported_pair(det, des) is not None: + continue + with self.subTest(detector=det, descriptor=des): + f = self.img.ComboFeature(det, des, nfeat=200) + self.assertGreater(len(f), 0) + self.assertLessEqual(len(f), 200) + self.assertEqual(f.descriptor.shape[0], len(f)) + self.assertIsInstance(f, _DESCRIPTORS[des][1]) + + def test_result_is_of_the_class_of_the_descriptor(self): + self.assertIsInstance(self.img.ComboFeature("FAST", "BRIEF"), BRIEFFeature) + self.assertIsInstance(self.img.ComboFeature("GFTT", "FREAK"), FREAKFeature) + self.assertIsInstance(self.img.ComboFeature("FAST", "LUCID"), LUCIDFeature) + + def test_options_reach_the_detector_and_descriptor(self): + few = self.img.ComboFeature("ORB", "BRIEF", det_opts=dict(nfeatures=50)) + self.assertLessEqual(len(few), 50) + short = self.img.ComboFeature("FAST", "BRIEF", des_opts=dict(bytes=16)) + self.assertEqual(short.descriptor.shape[1], 16) + + def test_nfeat_keeps_the_strongest(self): + everything = self.img.ComboFeature("FAST", "BRIEF") + some = self.img.ComboFeature("FAST", "BRIEF", nfeat=100) + # a few can be lost, because the descriptor needs a margin around the point + self.assertLessEqual(len(some), 100) + self.assertGreater(len(some), 80) + floor = min(f.strength for f in some) + self.assertGreaterEqual(floor, np.sort(everything.strength)[-100]) + + def test_scale_and_orientation_flags(self): + # FAST finds neither, SIFT and ORB find both + fast = self.img.ComboFeature("FAST", "BRIEF", nfeat=50) + with self.assertRaises(ValueError): + fast.scale + with self.assertRaises(ValueError): + fast.orientation + sift = self.img.ComboFeature("SIFT", "BRIEF", nfeat=50) + self.assertEqual(len(sift.scale), len(sift)) + self.assertEqual(len(sift.orientation), len(sift)) + # FREAK works out an orientation for each feature + freak = self.img.ComboFeature("FAST", "FREAK", nfeat=50) + self.assertEqual(len(freak.orientation), len(freak)) + with self.assertRaises(ValueError): + freak.scale + + def test_matching_with_the_same_descriptor(self): + a = self.img.ComboFeature("FAST", "BRIEF", nfeat=300) + b = Image.Read("eiffel-2.png").ComboFeature("AGAST", "BRIEF", nfeat=300) + m = a.match(b) + self.assertGreater(len(m), 0) + + def test_matching_different_descriptors_says_so(self): + a = self.img.ComboFeature("FAST", "BRIEF", nfeat=100) + b = self.img.ComboFeature("FAST", "DAISY", nfeat=100) + with self.assertRaisesRegex(ValueError, "different kinds of descriptor"): + a.match(b) + + def test_str_names_the_algorithm_or_the_pair(self): + # a feature is a detected keypoint and its descriptor + n = len(self.img.SIFT()) + self.assertEqual(str(self.img.SIFT()), f"SIFT features, {n} points") + f = self.img.ComboFeature("FAST", "BRIEF", nfeat=20) + self.assertEqual(str(f), f"FAST+BRIEF features, {len(f)} points") + self.assertTrue(str(f[0]).startswith("FAST+BRIEF feature: (")) + # slicing and adding keep the name + self.assertEqual(str(f[:5]), "FAST+BRIEF features, 5 points") + self.assertTrue(str(f.subset(5)).startswith("FAST+BRIEF features")) + # the same detector and descriptor is named once + s = self.img.ComboFeature("SIFT", "SIFT", nfeat=20) + self.assertTrue(str(s).startswith("SIFT features")) + + def test_sets_from_different_detectors_can_be_added(self): + a = self.img.ComboFeature("FAST", "BRIEF", nfeat=20) + b = self.img.ComboFeature("AGAST", "BRIEF", nfeat=20) + self.assertEqual(len(a + b), len(a) + len(b)) + + def test_id(self): + f = self.img.ComboFeature("FAST", "BRIEF", nfeat=20, id="index") + self.assertEqual([k.class_id for k in f._kp], list(range(len(f)))) + f = self.img.ComboFeature("FAST", "BRIEF", nfeat=20, id=7) + self.assertTrue(all(k.class_id == 7 for k in f._kp)) + with self.assertRaises(ValueError): + self.img.ComboFeature("FAST", "BRIEF", id="bad") + + def test_bad_names(self): + with self.assertRaisesRegex(ValueError, "unknown detector"): + self.img.ComboFeature("NOPE", "BRIEF") + with self.assertRaisesRegex(ValueError, "unknown descriptor"): + self.img.ComboFeature("FAST", "NOPE") + + def test_unsupported_pairs_say_why(self): + with self.assertRaisesRegex(ValueError, "AKAZE detector"): + self.img.ComboFeature("FAST", "AKAZE") + + def test_orb_describes_sift_keypoints_sensibly(self): + # not just no error: the matches must agree with one epipolar geometry, to the + # same standard as another pair that works + import cv2 + + def inlier_fraction(detector, descriptor): + a = self.img.ComboFeature(detector, descriptor, nfeat=1500) + b = Image.Read("eiffel-2.png").ComboFeature( + detector, descriptor, nfeat=1500 + ) + m = a.match(b, ratio=0.8) + self.assertGreater(len(m), 100) + p1 = np.array(m.p1, dtype=np.float32).T + p2 = np.array(m.p2, dtype=np.float32).T + _, mask = cv2.findFundamentalMat(p1, p2, cv2.FM_RANSAC, 2.0, 0.99) + return mask.sum() / len(m) + + self.assertGreater(inlier_fraction("SIFT", "ORB"), 0.7) + self.assertGreater(inlier_fraction("FAST", "ORB"), 0.7) + + def test_lucid_needs_color(self): + with self.assertRaisesRegex(ValueError, "color image"): + self.img.mono().ComboFeature("FAST", "LUCID") + + def test_image_can_be_greyscale(self): + f = self.img.mono().ComboFeature("FAST", "BRIEF", nfeat=50) + self.assertGreater(len(f), 40) + self.assertLessEqual(len(f), 50) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_image_point_features_extra.py b/tests/test_image_point_features_extra.py index 7e0d1a8d..7b63725a 100644 --- a/tests/test_image_point_features_extra.py +++ b/tests/test_image_point_features_extra.py @@ -140,12 +140,12 @@ def test_scalars_for_one_feature(self): class TestPrinting: def test_several(self): - assert str(make_features(3)) == "SIFTFeature features, 3 points" + assert str(make_features(3)) == "SIFT features, 3 points" assert repr(make_features(3)) == str(make_features(3)) 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 s.startswith("SIFT feature: (20.0, 25.0), strength=0.20") # 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")