From 57dac8993da8c11cfea75d510707583d029deaf2 Mon Sep 17 00:00:00 2001 From: Peter Corke Date: Fri, 20 Nov 2026 11:17:57 +1000 Subject: [PATCH 1/2] fix: say why an OpenCV contrib module is missing Pyodide, and so JupyterLite, has plain OpenCV without ximgproc, xfeatures2d and the other contrib modules, so using one failed with a bare AttributeError. A stand-in for each missing module now raises an AttributeError that names the module and says it needs opencv-contrib-python. Co-Authored-By: Claude Sonnet 5.5 --- src/machinevisiontoolbox/__init__.py | 7 ++ src/machinevisiontoolbox/_cv2_contrib.py | 81 ++++++++++++++++++++++++ tests/test_cv2_contrib.py | 69 ++++++++++++++++++++ 3 files changed, 157 insertions(+) create mode 100644 src/machinevisiontoolbox/_cv2_contrib.py create mode 100644 tests/test_cv2_contrib.py 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..774b53c7 --- /dev/null +++ b/src/machinevisiontoolbox/_cv2_contrib.py @@ -0,0 +1,81 @@ +"""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: {self.__name__} is one of " + "OpenCV's contrib modules, which need opencv-contrib-python. It is not " + "installed here; JupyterLite, for one, has only plain OpenCV." + ) + + +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..4777e8de --- /dev/null +++ b/tests/test_cv2_contrib.py @@ -0,0 +1,69 @@ +"""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() + assert "opencv-contrib-python" in str(info.value) + assert "ximgproc" in str(info.value) + + +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") From d97a9e5218de7a4de3afcb200479b93dd94f17fc Mon Sep 17 00:00:00 2001 From: Peter Corke Date: Fri, 20 Nov 2026 11:21:15 +1000 Subject: [PATCH 2/2] fix: the contrib error says what to install on a desktop Co-Authored-By: Claude Sonnet 5.5 --- src/machinevisiontoolbox/_cv2_contrib.py | 8 +++++--- tests/test_cv2_contrib.py | 6 ++++-- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/src/machinevisiontoolbox/_cv2_contrib.py b/src/machinevisiontoolbox/_cv2_contrib.py index 774b53c7..9ac347f2 100644 --- a/src/machinevisiontoolbox/_cv2_contrib.py +++ b/src/machinevisiontoolbox/_cv2_contrib.py @@ -61,9 +61,11 @@ 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: {self.__name__} is one of " - "OpenCV's contrib modules, which need opencv-contrib-python. It is not " - "installed here; JupyterLite, for one, has only plain OpenCV." + 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." ) diff --git a/tests/test_cv2_contrib.py b/tests/test_cv2_contrib.py index 4777e8de..11246c53 100644 --- a/tests/test_cv2_contrib.py +++ b/tests/test_cv2_contrib.py @@ -26,8 +26,10 @@ def test_using_a_stand_in_says_why(): contrib.install(cv2) with pytest.raises(contrib.ContribNotAvailableError) as info: cv2.ximgproc.segmentation.createGraphSegmentation() - assert "opencv-contrib-python" in str(info.value) - assert "ximgproc" in str(info.value) + 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():