From de7bcbe9d46afbb3cfded9e55242d9746fc6ae21 Mon Sep 17 00:00:00 2001 From: Peter Corke Date: Sat, 21 Nov 2026 16:47:47 +1000 Subject: [PATCH] feat: add Image.SURF and SURFFeature SURF is patented and absent from standard OpenCV builds, so SURF() raises a clear error that says to use a build with the contrib modules and OPENCV_ENABLE_NONFREE, or another detector, and the contrib-missing error still says to install opencv-contrib-python. BRISK and AKAZE are now resolved only when used, so a detector missing from OpenCV 5 without contrib no longer breaks every other feature detector. Closes #113 Co-Authored-By: Claude Sonnet 5.5 --- docs/source/support-classes.rst | 2 + .../ImagePointFeatures.py | 82 ++++++++++++++++++- tests/test_image_point_features.py | 58 +++++++++++-- 3 files changed, 135 insertions(+), 7 deletions(-) diff --git a/docs/source/support-classes.rst b/docs/source/support-classes.rst index 4bdd3e79..c9c487b6 100644 --- a/docs/source/support-classes.rst +++ b/docs/source/support-classes.rst @@ -54,6 +54,7 @@ Point features ~ImagePointFeatures.BaseFeature2D ~ImagePointFeatures.FeatureMatch ~ImagePointFeatures.SIFTFeature + ~ImagePointFeatures.SURFFeature ~ImagePointFeatures.ORBFeature ~ImagePointFeatures.BRISKFeature ~ImagePointFeatures.AKAZEFeature @@ -67,6 +68,7 @@ Point features .. inheritance-diagram:: ImagePointFeatures.SIFTFeature + ImagePointFeatures.SURFFeature ImagePointFeatures.ORBFeature ImagePointFeatures.BRISKFeature ImagePointFeatures.AKAZEFeature diff --git a/src/machinevisiontoolbox/ImagePointFeatures.py b/src/machinevisiontoolbox/ImagePointFeatures.py index 8ac395e9..b50c3dd0 100644 --- a/src/machinevisiontoolbox/ImagePointFeatures.py +++ b/src/machinevisiontoolbox/ImagePointFeatures.py @@ -1932,6 +1932,16 @@ class SIFTFeature(BaseFeature2D): """ +class SURFFeature(BaseFeature2D): + """ + Create set of SURF point features + + .. inheritance-diagram:: machinevisiontoolbox.ImagePointFeatures.SURFFeature + :top-classes: machinevisiontoolbox.ImagePointFeatures.BaseFeature2D + :parts: 1 + """ + + class ORBFeature(BaseFeature2D): """ Create set of ORB point features @@ -2071,6 +2081,27 @@ def _resolve_feature_create(name: str) -> Any: raise AttributeError(f"{name}_create not found in cv2 or cv2.xfeatures2d") +def _SURF_create(**kwargs: Any) -> Any: + """Create an OpenCV SURF detector, or explain why it is not available. + + SURF is patented. It is in the contrib modules (``cv2.xfeatures2d``), and even + then only when OpenCV was built with ``OPENCV_ENABLE_NONFREE``, which the + ``opencv-contrib-python`` wheels on PyPI are not. + """ + try: + # without the contrib modules, this raises ContribNotAvailableError, + # whose message explains what to install + return cv2.xfeatures2d.SURF_create(**kwargs) # type: ignore[attr-defined] + except cv2.error as e: + raise RuntimeError( + "SURF is not available in this OpenCV: it is patented and is left out of " + "standard builds, including the opencv-contrib-python wheels on PyPI. " + "Use a build of OpenCV with its contrib modules and the CMake option " + "OPENCV_ENABLE_NONFREE=ON, or use another detector such as SIFT, ORB, " + "BRISK or AKAZE." + ) from e + + # ------------------------------------------------------------------------- @@ -2088,10 +2119,13 @@ def _image2feature( # https://datascience.stackexchange.com/questions/43213/freak-feature-extraction-opencv algorithms: dict[str, Any] = { "SIFT": getattr(cv2, "SIFT_create"), + "SURF": _SURF_create, "ORB": getattr(cv2, "ORB_create"), "Harris": _Harris_create, - "BRISK": _resolve_feature_create("BRISK"), - "AKAZE": _resolve_feature_create("AKAZE"), + # resolved only when used, so that a detector missing from this OpenCV + # (OpenCV 5 without the contrib modules) does not break the others + "BRISK": lambda **kw: _resolve_feature_create("BRISK")(**kw), + "AKAZE": lambda **kw: _resolve_feature_create("AKAZE")(**kw), # 'FREAK': (cv2.FREAK_create, FREAKFeature), # 'DAISY': (cv2.DAISY_create, DAISYFeature), } @@ -2178,6 +2212,50 @@ def SIFT(self, **kwargs: Any) -> "SIFTFeature": return self._image2feature(SIFTFeature, scale=True, orient=True, **kwargs) + def SURF(self, **kwargs: Any) -> "SURFFeature": + """ + Find SURF features in image + + .. inheritance-diagram:: machinevisiontoolbox.ImagePointFeatures.SURFFeature + :top-classes: machinevisiontoolbox.ImagePointFeatures.BaseFeature2D + :parts: 1 + + :param kwargs: arguments passed to OpenCV, for example ``hessianThreshold`` + :return: set of 2D point features + :rtype: :class:`SURFFeature` + :raises RuntimeError: SURF is not available in this OpenCV + :raises AttributeError: OpenCV's contrib modules are not installed + + Returns an iterable and sliceable object that contains SURF features and + descriptors. + + .. warning:: SURF is patented, so it is excluded from standard OpenCV builds. + It needs OpenCV's contrib modules and a build with the CMake option + ``OPENCV_ENABLE_NONFREE=ON``, which the ``opencv-contrib-python`` wheels on + PyPI are not. If it is not available this method raises an exception that + says so. :meth:`SIFT` is a freely available alternative. + + Example: + + .. code-block:: python + + >>> from machinevisiontoolbox import Image + >>> img = Image.Read("eiffel-1.png") + >>> surf = img.SURF() + >>> len(surf) # number of features + + :references: + - SURF: Speeded up robust features. + Herbert Bay, Tinne Tuytelaars, and Luc Van Gool. + In European Conference on Computer Vision (ECCV), 2006. + - |RVC3|, Section 14.1. + + :seealso: :class:`SURFFeature` :meth:`SIFT` `cv2.xfeatures2d.SURF_create `_ + + .. versionadded:: 2.5.0 + """ + return self._image2feature(SURFFeature, scale=True, orient=True, **kwargs) + def ORB(self, scoreType: str = "harris", **kwargs: Any) -> "ORBFeature": """ Find ORB features in image diff --git a/tests/test_image_point_features.py b/tests/test_image_point_features.py index 67951c4d..135683ee 100644 --- a/tests/test_image_point_features.py +++ b/tests/test_image_point_features.py @@ -125,17 +125,65 @@ def test_sift(self): sift = img.SIFT() self.assertGreater(len(sift), 0) - @unittest.skip( - "Image.SURF() is not implemented, and SURF is non-free in pip OpenCV " - "builds; see https://github.com/petercorke/machinevision-toolbox-python/issues/113" - ) def test_surf(self): - """Test SURF feature detection""" + """SURF works if this OpenCV has it, otherwise the error says why""" + import cv2 + img = Image.Read("flowers1.png", mono=True) + try: + cv2.xfeatures2d.SURF_create() + except (cv2.error, AttributeError): + # not available (patented, or no contrib modules): expect a clear error + with self.assertRaises((RuntimeError, AttributeError)) as cm: + img.SURF() + self.assertTrue(str(cm.exception)) # the message says why + return surf = img.SURF() self.assertGreater(len(surf), 0) + def test_surf_nonfree_message(self): + """A build of OpenCV without the non-free algorithms gives a helpful message""" + import cv2 + from unittest import mock + + img = Image.Read("flowers1.png", mono=True) + err = cv2.error("(-213:The function/feature is not implemented) patented") + with mock.patch.object(cv2.xfeatures2d, "SURF_create", side_effect=err, create=True): + with self.assertRaises(RuntimeError) as cm: + img.SURF() + self.assertIn("OPENCV_ENABLE_NONFREE", str(cm.exception)) + self.assertIn("SIFT", str(cm.exception)) + + def test_surf_without_contrib(self): + """Without the contrib modules the error says to install them""" + import cv2 + from unittest import mock + + from machinevisiontoolbox._cv2_contrib import _MissingContrib + + img = Image.Read("flowers1.png", mono=True) + with mock.patch.object(cv2, "xfeatures2d", _MissingContrib("xfeatures2d"), create=True): + with self.assertRaises(AttributeError) as cm: + img.SURF() + self.assertIn("opencv-contrib-python", str(cm.exception)) + + def test_surf_features(self): + """SURF returns SURFFeature objects (detector stood in for by SIFT, which is free)""" + import cv2 + from unittest import mock + + from machinevisiontoolbox.ImagePointFeatures import SURFFeature + + img = Image.Read("flowers1.png", mono=True) + with mock.patch.object( + cv2.xfeatures2d, "SURF_create", side_effect=lambda **kw: cv2.SIFT_create(**kw), create=True + ): + surf = img.SURF() + self.assertIsInstance(surf, SURFFeature) + self.assertEqual(surf._feature_type, "SURF") + self.assertGreater(len(surf), 0) + def test_orb(self): """Test ORB feature detection""" img = Image.Read("monalisa.png", mono=True)