Merge pull request #620 from roboflow/feature/add_color_as_hex

Add 'as_hex' method and corresponding test to `Color` class.
This commit is contained in:
Piotr Skalski 2023-11-26 11:29:25 +01:00 committed by GitHub
commit d5d70052bb
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 34 additions and 0 deletions

View File

@ -71,6 +71,21 @@ class Color:
r, g, b = (int(color_hex[i : i + 2], 16) for i in range(0, 6, 2))
return cls(r, g, b)
def as_hex(self) -> str:
"""
Converts the Color instance to a hex string.
Returns:
str: The hexadecimal color string.
Example:
```
>>> Color(r=255, g=0, b=255).as_hex()
'#ff00ff'
```
"""
return f"#{self.r:02x}{self.g:02x}{self.b:02x}"
def as_rgb(self) -> Tuple[int, int, int]:
"""
Returns the color as an RGB tuple.

View File

@ -30,3 +30,22 @@ def test_color_from_hex(
with exception:
result = Color.from_hex(color_hex=color_hex)
assert result == expected_result
@pytest.mark.parametrize(
"color, expected_result, exception",
[
(Color.white(), "#ffffff", DoesNotRaise()),
(Color.black(), "#000000", DoesNotRaise()),
(Color.red(), "#ff0000", DoesNotRaise()),
(Color.green(), "#00ff00", DoesNotRaise()),
(Color.blue(), "#0000ff", DoesNotRaise()),
(Color(r=128, g=128, b=0), "#808000", DoesNotRaise()),
],
)
def test_color_as_hex(
color: Color, expected_result: Optional[str], exception: Exception
) -> None:
with exception:
result = color.as_hex()
assert result == expected_result