diff --git a/src/machinevisiontoolbox/__init__.py b/src/machinevisiontoolbox/__init__.py index 2aa2ebcb..fae32c89 100644 --- a/src/machinevisiontoolbox/__init__.py +++ b/src/machinevisiontoolbox/__init__.py @@ -1,4 +1,11 @@ # isort: skip_file +# before anything uses cv2: a clear error for OpenCV contrib modules that are not installed +import cv2 as _cv2 +from machinevisiontoolbox import _cv2_contrib + +_cv2_contrib.install(_cv2) +del _cv2 + # classes from machinevisiontoolbox.ImageCore import Image from machinevisiontoolbox.PointCloud import PointCloud diff --git a/src/machinevisiontoolbox/_cv2_contrib.py b/src/machinevisiontoolbox/_cv2_contrib.py new file mode 100644 index 00000000..9ac347f2 --- /dev/null +++ b/src/machinevisiontoolbox/_cv2_contrib.py @@ -0,0 +1,83 @@ +"""A clear error when OpenCV's contrib modules are not installed. + +OpenCV's extra modules (``cv2.ximgproc``, ``cv2.xfeatures2d`` and so on) come only with +``opencv-contrib-python``. Pyodide, and so JupyterLite, ships plain OpenCV without them, +as does an environment with ``opencv-python`` alone. Calling one of these then fails with +``AttributeError: module 'cv2' has no attribute 'ximgproc'``, which says nothing about why. + +:func:`install` puts a stand-in for each missing contrib module in ``cv2``. Using it +raises :class:`ContribNotAvailableError`, which says what is missing and why. That is an +:class:`AttributeError`, so ``hasattr(cv2.ximgproc, "x")`` is still False, and code that +tests for a feature this way keeps working. A module that is present is left alone. +""" + +from __future__ import annotations + +import types +from typing import Any + +# The modules of opencv_contrib that are not in plain OpenCV. This is OpenCV's list, not +# MVTB's. ``aruco`` is not here: it moved into the main modules in OpenCV 4.7. +CONTRIB_MODULES = ( + "bgsegm", + "bioinspired", + "ccalib", + "face", + "fuzzy", + "hfs", + "img_hash", + "intensity_transform", + "line_descriptor", + "mcc", + "optflow", + "phase_unwrapping", + "plot", + "quality", + "rapid", + "reg", + "rgbd", + "saliency", + "stereo", + "structured_light", + "surface_matching", + "text", + "tracking", + "wechat_qrcode", + "xfeatures2d", + "ximgproc", + "xobjdetect", + "xphoto", +) + + +class ContribNotAvailableError(AttributeError): + """A part of OpenCV's contrib modules was used, but they are not installed.""" + + +class _MissingContrib(types.ModuleType): + """Stands in for a contrib module that is not installed.""" + + def __getattr__(self, name: str) -> Any: + if name.startswith("__") and name.endswith("__"): + raise AttributeError(name) # not a use of the module: copy, pickle, ... + raise ContribNotAvailableError( + f"cv2.{self.__name__}.{name} is not available: OpenCV's contrib modules " + f"are not installed, and {self.__name__} is one of them. On a desktop, " + "install them with: pip install opencv-contrib-python. They cannot be " + "installed in JupyterLite, which has only plain OpenCV, so this feature " + "is not available there." + ) + + +def install(cv2_module: Any) -> list[str]: + """Add a stand-in for each contrib module that ``cv2_module`` lacks. + + :param cv2_module: the ``cv2`` module + :returns: the names of the stand-ins added + """ + added = [] + for name in CONTRIB_MODULES: + if not hasattr(cv2_module, name): + setattr(cv2_module, name, _MissingContrib(name)) + added.append(name) + return added diff --git a/tests/test_cv2_contrib.py b/tests/test_cv2_contrib.py new file mode 100644 index 00000000..11246c53 --- /dev/null +++ b/tests/test_cv2_contrib.py @@ -0,0 +1,71 @@ +"""A missing OpenCV contrib module gives a clear error, and a present one is untouched.""" + +import types + +import pytest + +from machinevisiontoolbox import _cv2_contrib as contrib + + +def plain_cv2() -> types.ModuleType: + """A cv2 without any contrib module, as in JupyterLite.""" + cv2 = types.ModuleType("cv2") + cv2.SIFT_create = lambda: "sift" + return cv2 + + +def test_a_missing_module_is_replaced_by_a_stand_in(): + cv2 = plain_cv2() + added = contrib.install(cv2) + assert "ximgproc" in added and "xfeatures2d" in added + assert hasattr(cv2, "ximgproc") + + +def test_using_a_stand_in_says_why(): + cv2 = plain_cv2() + contrib.install(cv2) + with pytest.raises(contrib.ContribNotAvailableError) as info: + cv2.ximgproc.segmentation.createGraphSegmentation() + message = str(info.value) + assert "ximgproc" in message and "not installed" in message + assert "pip install opencv-contrib-python" in message + assert "JupyterLite" in message + + +def test_the_error_is_an_attribute_error_so_hasattr_still_works(): + cv2 = plain_cv2() + contrib.install(cv2) + assert not hasattr(cv2.xfeatures2d, "BriefDescriptorExtractor_create") + with pytest.raises(AttributeError): + cv2.xfeatures2d.BriefDescriptorExtractor_create + + +def test_a_module_that_is_present_is_left_alone(): + cv2 = plain_cv2() + real = types.ModuleType("ximgproc") + real.thinning = lambda: "thin" + cv2.ximgproc = real + added = contrib.install(cv2) + assert "ximgproc" not in added + assert cv2.ximgproc is real and cv2.ximgproc.thinning() == "thin" + + +def test_main_opencv_is_not_touched(): + cv2 = plain_cv2() + contrib.install(cv2) + assert cv2.SIFT_create() == "sift" + assert not hasattr(cv2, "aruco") # in main OpenCV, so never stood in for + + +def test_installing_twice_adds_nothing_more(): + cv2 = plain_cv2() + contrib.install(cv2) + assert contrib.install(cv2) == [] + + +def test_the_real_cv2_still_works_after_import(): + import cv2 + + import machinevisiontoolbox # noqa: F401 + + assert hasattr(cv2, "SIFT_create")