Skip to content

Commit

Permalink
improve code
Browse files Browse the repository at this point in the history
  • Loading branch information
Czaki committed Sep 23, 2024
1 parent f174e95 commit f9ff1f2
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 12 deletions.
28 changes: 17 additions & 11 deletions package/PartSegImage/image.py
Original file line number Diff line number Diff line change
Expand Up @@ -988,19 +988,25 @@ def _name_to_rgb(name: str) -> tuple[int, int, int]:
:param str name: The color name
:return: A tuple containing the RGB values (R, G, B)
"""
name = name.lower()
if name not in _NAMED_COLORS:
raise ValueError(f"Unknown color name: {name}")
return _hex_to_rgb(_NAMED_COLORS[name])


_NAMED_COLORS = {
"red": "#FF0000",
"green": "#00FF00",
"blue": "#0000FF",
"yellow": "#FFFF00",
"cyan": "#00FFFF",
"magenta": "#FF00FF",
"white": "#FFFFFF",
"black": "#000000",
"orange": "#FFA500",
}
try:
from vispy.color import get_color_dict
except ImportError: # pragma: no cover
_NAMED_COLORS = {
"red": "#FF0000",
"green": "#008000",
"blue": "#0000FF",
"yellow": "#FFFF00",
"cyan": "#00FFFF",
"magenta": "#FF00FF",
"white": "#FFFFFF",
"black": "#000000",
"orange": "#FFA500",
}
else:
_NAMED_COLORS = get_color_dict()
14 changes: 13 additions & 1 deletion package/tests/test_PartSegImage/test_image.py
Original file line number Diff line number Diff line change
Expand Up @@ -709,7 +709,19 @@ def test_hex_to_rgb():

def test_name_to_rgb():
assert _name_to_rgb("red") == (255, 0, 0)
assert _name_to_rgb("Red") == (255, 0, 0)
assert _name_to_rgb("RED") == (255, 0, 0)
assert _name_to_rgb("blue") == (0, 0, 255)
assert _name_to_rgb("green") == (0, 255, 0)
assert _name_to_rgb("green") == (0, 128, 0)
assert _name_to_rgb("white") == (255, 255, 255)
assert _name_to_rgb("black") == (0, 0, 0)
assert _name_to_rgb("yellow") == (255, 255, 0)
with pytest.raises(ValueError, match="Unknown color name"):
_name_to_rgb("strange")
with pytest.raises(ValueError, match="Unknown color name"):
_name_to_rgb("")


def test_name_to_rgb_vispy():
# This test fail if vispy is not installed
assert _name_to_rgb("lime") == (0, 255, 0)

0 comments on commit f9ff1f2

Please sign in to comment.