7

我知道 RGB 到 HSV 的转换应该采用 RGB 值 0-255 并转换为 HSV 值 [0-360, 0-1, 0-1]。例如在 java 中查看这个转换器

当我在图像上运行 matplotlib.colors.rbg_to_hsv 时,它似乎改为输出值 [0-1, 0-1, 0-360]。但是,我在这样的图像上使用了这个函数,它似乎以正确的顺序 [H,S,V] 工作,只是 V 太大了。

例子:

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]
  ..., 

那些不是 0,它们是 0 到 1 之间的某个数字。

这是 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

我会使用其他 rgb_to_hsv 转换之一,如 colorsys,但这是我发现的唯一一个矢量化 python。我们能弄清楚吗?我们需要在github上报告吗?

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

4

2 回答 2

7

如果不是从 0 到 255 的无符号整数 RGB 值,而是从 0 到 1 的浮点 RGB 值,它会很好地工作。如果文档指定了这一点,或者函数试图捕捉看起来非常可能是人为错误。但是你可以通过调用得到你想要的:

print colors.rgb_to_hsv(image / 255)
于 2013-06-27T18:50:38.357 回答
0

注意,源注释状态输入/输出的维度应该是 M,N,3,对于 RGBA (M,N,4) 图像,例如导入的 png 文件,该函数会失败。

于 2014-07-30T12:29:16.783 回答