Matplotlib colors rgb_to_hsv does not work correctly. Maybe you need to report this?

I understand that the conversion of RGB to HSV must take values ​​of RGB 0-255 and convert the values ​​of HSV [0-360, 0-1, 0-1]. For example, see this converter in java :

When I run matplotlib.colors.rbg_to_hsv on the image, it seems to output the values ​​[0-1, 0-1, 0-360]. However, I used this function in an image like this , and it seems to work in the correct order [H, S, V] just V is too big.

Example:

In [1]: import matplotlib.pyplot as plt In [2]: import matplotlib.colors as colors In [3]: image = plt.imread("/path/to/rgb/jpg/image") In [4]: print image [[[126 91 111] [123 85 106] [123 85 106] ..., In [5]: print colors.rgb_to_hsv(image) [[[ 0 0 126] [ 0 0 123] [ 0 0 123] ..., 

It is not 0s, it is a number from 0 to 1.

Here is the definition from matplotlib.colors.rgb_to_hsv

 def rgb_to_hsv(arr): """ convert rgb values in a numpy array to hsv values input and output arrays should have shape (M,N,3) """ out = np.zeros(arr.shape, dtype=np.float) arr_max = arr.max(-1) ipos = arr_max > 0 delta = arr.ptp(-1) s = np.zeros_like(delta) s[ipos] = delta[ipos] / arr_max[ipos] ipos = delta > 0 # red is max idx = (arr[:, :, 0] == arr_max) & ipos out[idx, 0] = (arr[idx, 1] - arr[idx, 2]) / delta[idx] # green is max idx = (arr[:, :, 1] == arr_max) & ipos out[idx, 0] = 2. + (arr[idx, 2] - arr[idx, 0]) / delta[idx] # blue is max idx = (arr[:, :, 2] == arr_max) & ipos out[idx, 0] = 4. + (arr[idx, 0] - arr[idx, 1]) / delta[idx] out[:, :, 0] = (out[:, :, 0] / 6.0) % 1.0 out[:, :, 1] = s out[:, :, 2] = arr_max return out 

I would use one of the other rgb_to_hsv transforms such as colorsys, but this is the only vector python I found. Can we figure this out? Do i need to report this on github?

Matplotlib 1.2.0, numpy 1.6.1, Python 2.7, Mac OS X 10.8

+6
source share
2 answers

This works great if, instead of unsigned int RGB values ​​from 0 to 255, you feed it with RGB values ​​from 0 to 1. It would be nice if the documentation says this, or if the function tried to catch what seems to be a very likely human error. But you can get what you want by simply calling:

 print colors.rgb_to_hsv(image / 255) 
+6
source

Take care that the source comment indicates that the input / output should be of size M, N, 3, and the function does not work for RGBA images (M, N, 4), for example. imported png files.

0
source

Source: https://habr.com/ru/post/948260/


All Articles