balthou commited on
Commit
56a9526
·
1 Parent(s): 387b47b

discard division warning in HSV transform

Browse files
Files changed (1) hide show
  1. 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
- # Ensure the input is a float numpy array and in the range [0, 1]
6
- rgb = np.asarray(rgb)
 
 
 
 
 
 
 
 
7
 
8
- # Separate the R, G, B channels
9
- r, g, b = rgb[..., 0], rgb[..., 1], rgb[..., 2]
 
 
10
 
11
- # Max and min of RGB values
12
- max_rgb = np.max(rgb, axis=-1)
13
- min_rgb = np.min(rgb, axis=-1)
14
- delta = max_rgb - min_rgb
15
 
16
- # Hue calculation
17
- hue = np.zeros_like(max_rgb)
18
- mask = delta != 0
19
 
20
- # Red is max
21
- idx = (max_rgb == r) & mask
22
- hue[idx] = (60 * ((g - b) / delta % 6))[idx]
23
 
24
- # Green is max
25
- idx = (max_rgb == g) & mask
26
- hue[idx] = (60 * ((b - r) / delta + 2))[idx]
27
 
28
- # Blue is max
29
- idx = (max_rgb == b) & mask
30
- hue[idx] = (60 * ((r - g) / delta + 4))[idx]
31
 
32
- # Saturation calculation
33
- saturation = np.zeros_like(max_rgb)
34
- saturation[mask] = delta[mask] / max_rgb[mask]
35
 
36
- # Value calculation
37
- value = max_rgb
38
 
39
- # Stack the HSV components together
40
- hsv = np.stack((hue, saturation, value), axis=-1)
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