Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions docs/source/support-classes.rst
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ Point features
~ImagePointFeatures.BaseFeature2D
~ImagePointFeatures.FeatureMatch
~ImagePointFeatures.SIFTFeature
~ImagePointFeatures.SURFFeature
~ImagePointFeatures.ORBFeature
~ImagePointFeatures.BRISKFeature
~ImagePointFeatures.AKAZEFeature
Expand All @@ -67,6 +68,7 @@ Point features


.. inheritance-diagram:: ImagePointFeatures.SIFTFeature
ImagePointFeatures.SURFFeature
ImagePointFeatures.ORBFeature
ImagePointFeatures.BRISKFeature
ImagePointFeatures.AKAZEFeature
Expand Down
82 changes: 80 additions & 2 deletions src/machinevisiontoolbox/ImagePointFeatures.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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


# -------------------------------------------------------------------------


Expand All @@ -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),
}
Expand Down Expand Up @@ -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 <https://docs.opencv.org/4.x/d5/df7/classcv_1_1xfeatures2d_1_1SURF.html>`_

.. 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
Expand Down
58 changes: 53 additions & 5 deletions tests/test_image_point_features.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
Loading