From 17aee0f02773a6fdd53cfae8b126ae6c646ad0d5 Mon Sep 17 00:00:00 2001 From: Peter Corke Date: Mon, 23 Nov 2026 15:48:25 +1000 Subject: [PATCH 1/2] fix: raise for an unknown colorspace in name2color and plot_spectral_locus name2color caught ValueError around the whole conversion, so an unknown colorspace returned None, the same as an unknown color name. plot_spectral_locus tested colorspace in ("rg"), a substring test, so "r", "g" and "" were accepted as rg, and any other value raised UnboundLocalError instead of the ValueError its docstring promises. Co-Authored-By: Claude Sonnet 5.5 --- src/machinevisiontoolbox/base/color.py | 21 ++++++++++++-- tests/test_color_lookup_errors.py | 38 +++++++++++++++++++++++++- 2 files changed, 56 insertions(+), 3 deletions(-) diff --git a/src/machinevisiontoolbox/base/color.py b/src/machinevisiontoolbox/base/color.py index 1ded56bd..ae9d4e1c 100755 --- a/src/machinevisiontoolbox/base/color.py +++ b/src/machinevisiontoolbox/base/color.py @@ -760,6 +760,13 @@ def name2color( If a Python-style regexp is passed, then the return value is a list of matching color names. + If the name is not a known color the return value is ``None``. An unknown + ``colorspace`` raises a :class:`ValueError`. + + .. versionchanged:: 2.5.0 + An unknown ``colorspace`` raises :class:`ValueError`. It used to return + ``None``, as for an unknown color name. + Example: .. runblock:: pycon @@ -800,6 +807,14 @@ def csconvert(name: str, cs: str) -> np.ndarray: f"unknown colorspace {cs!r}, must be rgb, xyz, lab, xy or ab" ) + # check the colorspace here, so that it is not mistaken for an unknown color + # name by the handler below + cs = colorspace.lower() + if cs not in ("rgb", "xyz", "lab", "l*a*b*", "xy", "ab"): + raise ValueError( + f"unknown colorspace {colorspace!r}, must be rgb, xyz, lab, xy or ab" + ) + if any([c in ".?*" for c in name]): # has a wildcard return list( @@ -810,7 +825,7 @@ def csconvert(name: str, cs: str) -> np.ndarray: ) else: try: - color = csconvert(name, colorspace.lower()) + color = csconvert(name, cs) if np.issubdtype(dtype, np.integer): # if dtype is an integer type, scale the color to the range [0,M] color = (color * np.iinfo(dtype).max).astype(dtype) @@ -1230,8 +1245,10 @@ def plot_spectral_locus( if colorspace in ("XY", "xy"): locus = ccxyz(λ)[:, :2] - elif colorspace in ("rg"): + elif colorspace == "rg": locus = lambda2rg(λ, method="cubic") + else: + raise ValueError(f"unknown colorspace {colorspace!r}, must be xy or rg") if ax is None: ax = plt.subplot(1, 1, 1) diff --git a/tests/test_color_lookup_errors.py b/tests/test_color_lookup_errors.py index 6c179db3..1eb8acfa 100644 --- a/tests/test_color_lookup_errors.py +++ b/tests/test_color_lookup_errors.py @@ -1,6 +1,10 @@ import unittest -from machinevisiontoolbox.base.color import XYZ2RGBxform +from machinevisiontoolbox.base.color import ( + XYZ2RGBxform, + name2color, + plot_spectral_locus, +) class TestColorLookupErrors(unittest.TestCase): @@ -22,3 +26,35 @@ def test_unknown_primaries_lists_supported_values(self): "unknown primary value, must be one of itu-709, cie, srgb", ) self.assertIsInstance(raised.exception.__cause__, KeyError) + + +class TestName2ColorErrors(unittest.TestCase): + def test_unknown_colorspace_raises(self): + """An unknown colorspace is an error, not the None of an unknown name.""" + with self.assertRaisesRegex(ValueError, "unknown colorspace 'hsv'"): + name2color("red", "hsv") + + def test_unknown_name_is_none(self): + self.assertIsNone(name2color("not a color")) + self.assertIsNone(name2color("not a color", "xy")) + + def test_colorspace_is_not_case_sensitive(self): + self.assertEqual(name2color("red", "RGB").tolist(), [1, 0, 0]) + self.assertEqual(name2color("red", "XYZ").shape, (3,)) + self.assertEqual(name2color("red", "xy").shape, (2,)) + + def test_wildcard_with_unknown_colorspace_is_a_list(self): + # the wildcard branch returns names and does not use the colorspace + self.assertIsInstance(name2color(".*burnt.*", "xy"), list) + + +class TestPlotSpectralLocusErrors(unittest.TestCase): + def test_unknown_colorspace_raises(self): + with self.assertRaisesRegex(ValueError, "unknown colorspace 'lab'"): + plot_spectral_locus("lab") + + def test_a_substring_of_rg_is_not_rg(self): + # `colorspace in ("rg")` is a substring test, so "r" and "" used to pass + for bad in ("r", "g", ""): + with self.assertRaises(ValueError): + plot_spectral_locus(bad) From e3f4de55b6678c85898e68347316c3b16f43d0d1 Mon Sep 17 00:00:00 2001 From: Peter Corke Date: Mon, 23 Nov 2026 15:53:12 +1000 Subject: [PATCH 2/2] feat: add color_names and remove the wildcard from name2color name2color returned a color value, a list of names (for a name containing ., ? or *) or None, which made its return type awkward for callers. color_names(pattern) lists the Matplotlib color names, all of them or those whose whole name matches a Python regular expression. name2color now raises ValueError for a name with a wildcard, pointing to color_names. The chap10 notebook uses color_names for the coral example. Co-Authored-By: Claude Sonnet 5.5 --- src/machinevisiontoolbox/__init__.py | 1 + src/machinevisiontoolbox/base/__init__.py | 1 + src/machinevisiontoolbox/base/color.py | 116 ++++++++++++++++------ tests/RVC/chap10.ipynb | 2 +- tests/test_color_lookup_errors.py | 45 ++++++++- 5 files changed, 130 insertions(+), 35 deletions(-) diff --git a/src/machinevisiontoolbox/__init__.py b/src/machinevisiontoolbox/__init__.py index fc75fb0f..c63248c1 100644 --- a/src/machinevisiontoolbox/__init__.py +++ b/src/machinevisiontoolbox/__init__.py @@ -87,6 +87,7 @@ rluminos, ccxyz, name2color, + color_names, color2name, colorname, cie_primaries, diff --git a/src/machinevisiontoolbox/base/__init__.py b/src/machinevisiontoolbox/base/__init__.py index 7ad6063f..0ff0734e 100644 --- a/src/machinevisiontoolbox/base/__init__.py +++ b/src/machinevisiontoolbox/base/__init__.py @@ -22,6 +22,7 @@ "rluminos", "ccxyz", "name2color", + "color_names", "color2name", "colorname", "cie_primaries", diff --git a/src/machinevisiontoolbox/base/color.py b/src/machinevisiontoolbox/base/color.py index ae9d4e1c..6f33b4a7 100755 --- a/src/machinevisiontoolbox/base/color.py +++ b/src/machinevisiontoolbox/base/color.py @@ -727,7 +727,7 @@ def name2color( colorspace: str = "RGB", dtype: str | type | np.dtype = "float", colororder: dict[str, int] | None = None, -) -> np.ndarray | list[str] | None: +) -> np.ndarray | None: """ Map color name to value @@ -739,8 +739,9 @@ def name2color( :type dtype: str, type or numpy.dtype :param colororder: dictionary mapping color name to index :type colororder: dict, optional - :return: color tristimulus or chromaticity value; or list of matching color names - :rtype: ndarray(3), ndarray(2); list[str] + :return: color tristimulus or chromaticity value, or ``None`` if the name is not known + :rtype: ndarray(3), ndarray(2) or None + :raises ValueError: unknown ``colorspace``, or ``name`` contains a wildcard Looks up the RGB tristimulus for this color using ``matplotlib.colors`` and converts it to the desired ``colorspace``. @@ -757,16 +758,19 @@ def name2color( to the index in the output array. For an image, this dictionary is given by the :meth:`~machinevisiontoolbox.Image.colororder` method. - If a Python-style regexp is passed, then the return value is a list - of matching color names. - If the name is not a known color the return value is ``None``. An unknown - ``colorspace`` raises a :class:`ValueError`. + ``colorspace`` raises a :class:`ValueError`. To find color names that match + a pattern use :func:`color_names`. .. versionchanged:: 2.5.0 An unknown ``colorspace`` raises :class:`ValueError`. It used to return ``None``, as for an unknown color name. + .. versionchanged:: 2.5.0 + A name containing a wildcard (``.``, ``?`` or ``*``) raises + :class:`ValueError`. It used to return a list of the matching color + names, which is now done by :func:`color_names`. + Example: .. runblock:: pycon @@ -777,14 +781,13 @@ def name2color( >>> name2color("red", colororder={"R": 2, "G": 1, "B": 0}) >>> name2color("r", "xy") >>> name2color("lime green") - >>> name2color(".*burnt.*") .. note:: Uses color database from Matplotlib. :references: - |RVC3|, Section 10.1. - :seealso: :func:`~color2name` + :seealso: :func:`~color2name` :func:`color_names` """ def csconvert(name: str, cs: str) -> np.ndarray: @@ -816,28 +819,80 @@ def csconvert(name: str, cs: str) -> np.ndarray: ) if any([c in ".?*" for c in name]): - # has a wildcard - return list( - filter( - re.compile(name).match, - [key for key in colors.get_named_colors_mapping().keys()], - ) + raise ValueError( + f"{name!r} contains a wildcard, name2color no longer matches patterns, " + "use color_names(pattern)" ) - else: - try: - color = csconvert(name, cs) - if np.issubdtype(dtype, np.integer): - # if dtype is an integer type, scale the color to the range [0,M] - color = (color * np.iinfo(dtype).max).astype(dtype) - if colororder is not None: - # reorder the elements of the color if colororder is given - # colororder is a dict mapping plane name to index -- fancy - # index rather than a list comprehension, to keep the - # ndarray return type promised by this function's contract - color = color[[colororder[c] for c in colorspace]] - return color - except ValueError: - return None + + try: + color = csconvert(name, cs) + if np.issubdtype(dtype, np.integer): + # if dtype is an integer type, scale the color to the range [0,M] + color = (color * np.iinfo(dtype).max).astype(dtype) + if colororder is not None: + # reorder the elements of the color if colororder is given + # colororder is a dict mapping plane name to index -- fancy + # index rather than a list comprehension, to keep the + # ndarray return type promised by this function's contract + color = color[[colororder[c] for c in colorspace]] + return color + except ValueError: + return None + + +def color_names(pattern: str | None = None) -> list[str]: + r""" + List the known color names + + :param pattern: Python regular expression that the whole name must match, + defaults to None + :type pattern: str, optional + :return: color names, all of them or those that match ``pattern`` + :rtype: list[str] + :raises ValueError: ``pattern`` is not a valid regular expression + + The names are those of the color database of Matplotlib, which is also used + by :func:`name2color` and :func:`color2name`. + + If ``pattern`` is given only the names that match it are returned. + + .. important:: + + ``pattern`` is a **Python regular expression**, as used by the + :mod:`re` module, **not** a shell style wildcard such as ``*.png``. + In a regular expression ``.*`` means any number of any characters, + whereas ``*`` or ``?`` at the start of a pattern is an error. The whole + name must match, so to find names that contain ``coral`` use + ``".*coral.*"``, not ``"coral"`` or ``"*coral*"``. + + Example: + + .. runblock:: pycon + + >>> from machinevisiontoolbox import color_names + >>> color_names(".*burnt.*") + >>> color_names("(red|green|blue)") + >>> len(color_names()) + + .. versionadded:: 2.5.0 + Replaces the wildcard feature of :func:`name2color`. + + :references: + - |RVC3|, Section 10.1. + + :seealso: :func:`name2color` :func:`color2name` :mod:`re` + """ + names = list(colors.get_named_colors_mapping().keys()) + if pattern is None: + return names + try: + regexp = re.compile(pattern) + except re.error as e: + raise ValueError( + f"{pattern!r} is not a valid Python regular expression ({e}), " + "note that * and ? are not shell style wildcards, use .* for any text" + ) from e + return [name for name in names if regexp.fullmatch(name)] def color2name(color: np.ndarray | list[float], colorspace: str = "RGB") -> str: @@ -864,7 +919,6 @@ def color2name(color: np.ndarray | list[float], colorspace: str = "RGB") -> str: .. note:: - - Color name may contain a wildcard, eg. "?burnt" - Uses color database from Matplotlib - Tristiumuls values are [0,1] diff --git a/tests/RVC/chap10.ipynb b/tests/RVC/chap10.ipynb index 885a168c..02b60290 100644 --- a/tests/RVC/chap10.ipynb +++ b/tests/RVC/chap10.ipynb @@ -458,7 +458,7 @@ "metadata": {}, "outputs": [], "source": [ - "name2color(\".*coral.*\")" + "color_names(\".*coral.*\")" ] }, { diff --git a/tests/test_color_lookup_errors.py b/tests/test_color_lookup_errors.py index 1eb8acfa..21bfe80e 100644 --- a/tests/test_color_lookup_errors.py +++ b/tests/test_color_lookup_errors.py @@ -2,6 +2,7 @@ from machinevisiontoolbox.base.color import ( XYZ2RGBxform, + color_names, name2color, plot_spectral_locus, ) @@ -43,9 +44,47 @@ def test_colorspace_is_not_case_sensitive(self): self.assertEqual(name2color("red", "XYZ").shape, (3,)) self.assertEqual(name2color("red", "xy").shape, (2,)) - def test_wildcard_with_unknown_colorspace_is_a_list(self): - # the wildcard branch returns names and does not use the colorspace - self.assertIsInstance(name2color(".*burnt.*", "xy"), list) + def test_wildcard_is_an_error_that_names_the_replacement(self): + for name in (".*burnt.*", "?burnt", "*coral"): + with self.assertRaisesRegex(ValueError, "color_names"): + name2color(name) + + +class TestColorNames(unittest.TestCase): + def test_no_pattern_lists_every_name(self): + names = color_names() + self.assertIsInstance(names, list) + self.assertIn("red", names) + self.assertGreater(len(names), 100) + self.assertEqual(len(names), len(set(names))) + + def test_pattern_is_a_regular_expression(self): + names = color_names(".*burnt.*") + self.assertGreater(len(names), 0) + self.assertTrue(all("burnt" in n for n in names)) + + def test_the_whole_name_must_match(self): + # "coral" alone is not a match for "light coral" or "coral"-containing names + self.assertEqual(color_names("coral"), ["coral"]) + self.assertIn("lightcoral", color_names(".*coral")) + self.assertNotIn("lightcoral", color_names("coral")) + + def test_alternatives(self): + self.assertEqual( + sorted(color_names("(red|green|blue)")), ["blue", "green", "red"] + ) + + def test_no_match_is_an_empty_list(self): + self.assertEqual(color_names("zzzz.*"), []) + + def test_every_name_is_known_to_name2color(self): + for name in color_names("[a-z]+"): + self.assertEqual(name2color(name).shape, (3,)) + + def test_shell_style_wildcard_is_an_error_that_says_so(self): + for bad in ("*coral*", "?burnt"): + with self.assertRaisesRegex(ValueError, "not shell style wildcards"): + color_names(bad) class TestPlotSpectralLocusErrors(unittest.TestCase):