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
21 changes: 19 additions & 2 deletions src/machinevisiontoolbox/base/color.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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(
Expand All @@ -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)
Expand Down Expand Up @@ -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)
Expand Down
38 changes: 37 additions & 1 deletion tests/test_color_lookup_errors.py
Original file line number Diff line number Diff line change
@@ -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):
Expand All @@ -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)
Loading