Spaces:
Sleeping
Sleeping
discard division warning in HSV transform
Browse files- color_conversions.py +37 -27
color_conversions.py
CHANGED
|
@@ -1,44 +1,54 @@
|
|
| 1 |
import numpy as np
|
|
|
|
| 2 |
|
| 3 |
|
| 4 |
def rgb_to_hsv(rgb):
|
| 5 |
-
|
| 6 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
|
| 8 |
-
|
| 9 |
-
|
|
|
|
|
|
|
| 10 |
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
min_rgb = np.min(rgb, axis=-1)
|
| 14 |
-
delta = max_rgb - min_rgb
|
| 15 |
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
mask = delta != 0
|
| 19 |
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
|
| 36 |
-
|
| 37 |
-
|
| 38 |
|
| 39 |
-
|
| 40 |
-
|
| 41 |
|
|
|
|
|
|
|
| 42 |
return hsv
|
| 43 |
|
| 44 |
|
|
|
|
| 1 |
import numpy as np
|
| 2 |
+
import warnings
|
| 3 |
|
| 4 |
|
| 5 |
def rgb_to_hsv(rgb):
|
| 6 |
+
with warnings.catch_warnings():
|
| 7 |
+
# Suppress the specific RuntimeWarning
|
| 8 |
+
warnings.filterwarnings(
|
| 9 |
+
"ignore", category=RuntimeWarning, message="invalid value encountered in divide")
|
| 10 |
+
|
| 11 |
+
# Ensure the input is a float numpy array and in the range [0, 1]
|
| 12 |
+
rgb = np.asarray(rgb)
|
| 13 |
+
|
| 14 |
+
# Separate the R, G, B channels
|
| 15 |
+
r, g, b = rgb[..., 0], rgb[..., 1], rgb[..., 2]
|
| 16 |
|
| 17 |
+
# Max and min of RGB values
|
| 18 |
+
max_rgb = np.max(rgb, axis=-1)
|
| 19 |
+
min_rgb = np.min(rgb, axis=-1)
|
| 20 |
+
delta = max_rgb - min_rgb
|
| 21 |
|
| 22 |
+
# Hue calculation
|
| 23 |
+
hue = np.zeros_like(max_rgb)
|
|
|
|
|
|
|
| 24 |
|
| 25 |
+
# Avoid division by zero: Only calculate where delta is non-zero
|
| 26 |
+
mask = delta != 0
|
|
|
|
| 27 |
|
| 28 |
+
# Red is max
|
| 29 |
+
idx = (max_rgb == r) & mask
|
| 30 |
+
hue[idx] = (60 * ((g - b) / delta % 6))[idx]
|
| 31 |
|
| 32 |
+
# Green is max
|
| 33 |
+
idx = (max_rgb == g) & mask
|
| 34 |
+
hue[idx] = (60 * ((b - r) / delta + 2))[idx]
|
| 35 |
|
| 36 |
+
# Blue is max
|
| 37 |
+
idx = (max_rgb == b) & mask
|
| 38 |
+
hue[idx] = (60 * ((r - g) / delta + 4))[idx]
|
| 39 |
|
| 40 |
+
# Saturation calculation
|
| 41 |
+
saturation = np.zeros_like(max_rgb)
|
| 42 |
+
saturation[mask] = delta[mask] / max_rgb[mask]
|
| 43 |
|
| 44 |
+
# Handle the edge case where max_rgb is 0 (black pixels)
|
| 45 |
+
saturation[max_rgb == 0] = 0
|
| 46 |
|
| 47 |
+
# Value calculation
|
| 48 |
+
value = max_rgb
|
| 49 |
|
| 50 |
+
# Stack the HSV components together
|
| 51 |
+
hsv = np.stack((hue, saturation, value), axis=-1)
|
| 52 |
return hsv
|
| 53 |
|
| 54 |
|