|
31 | 31 | from __future__ import annotations |
32 | 32 |
|
33 | 33 | import re |
34 | | -from colorsys import hls_to_rgb, rgb_to_hls |
| 34 | +from colorsys import hls_to_rgb, hsv_to_rgb, rgb_to_hls, rgb_to_hsv |
35 | 35 | from functools import lru_cache |
36 | 36 | from operator import itemgetter |
37 | 37 | from typing import Callable, NamedTuple |
@@ -82,7 +82,7 @@ class HSV(NamedTuple): |
82 | 82 | s: float |
83 | 83 | """Saturation in range 0 to 1.""" |
84 | 84 | v: float |
85 | | - """Value un range 0 to 1.""" |
| 85 | + """Value in range 0 to 1.""" |
86 | 86 |
|
87 | 87 |
|
88 | 88 | class Lab(NamedTuple): |
@@ -212,6 +212,21 @@ def from_hsl(cls, h: float, s: float, l: float) -> Color: |
212 | 212 | r, g, b = hls_to_rgb(h, l, s) |
213 | 213 | return cls(int(r * 255 + 0.5), int(g * 255 + 0.5), int(b * 255 + 0.5)) |
214 | 214 |
|
| 215 | + @classmethod |
| 216 | + def from_hsv(cls, h: float, s: float, v: float) -> Color: |
| 217 | + """Create a color from HSV components. |
| 218 | +
|
| 219 | + Args: |
| 220 | + h: Hue. |
| 221 | + s: Saturation. |
| 222 | + v: Value. |
| 223 | +
|
| 224 | + Returns: |
| 225 | + A new color. |
| 226 | + """ |
| 227 | + r, g, b = hsv_to_rgb(h, s, v) |
| 228 | + return cls(int(r * 255 + 0.5), int(g * 255 + 0.5), int(b * 255 + 0.5)) |
| 229 | + |
215 | 230 | @property |
216 | 231 | def inverse(self) -> Color: |
217 | 232 | """The inverse of this color. |
@@ -286,6 +301,19 @@ def hsl(self) -> HSL: |
286 | 301 | h, l, s = rgb_to_hls(r, g, b) |
287 | 302 | return HSL(h, s, l) |
288 | 303 |
|
| 304 | + @property |
| 305 | + def hsv(self) -> HSV: |
| 306 | + """This color in HSV format. |
| 307 | +
|
| 308 | + HSV color is an alternative way of representing a color, which can be used in certain color calculations. |
| 309 | +
|
| 310 | + Returns: |
| 311 | + Color encoded in HSV format. |
| 312 | + """ |
| 313 | + r, g, b = self.normalized |
| 314 | + h, s, v = rgb_to_hsv(r, g, b) |
| 315 | + return HSV(h, s, v) |
| 316 | + |
289 | 317 | @property |
290 | 318 | def brightness(self) -> float: |
291 | 319 | """The human perceptual brightness. |
|
0 commit comments