【问题标题】:matplotlib colors rgb_to_hsv not working right . Maybe need to report it?matplotlib 颜色 rgb_to_hsv 无法正常工作。也许需要报告?
【发布时间】:2013-06-27 17:47:16
【问题描述】:

我了解 RGB 到 HSV 的转换应该采用 RGB 值 0-255 并转换为 HSV 值 [0-360, 0-1, 0-1]。例如看到这个converter in java

当我在图像上运行 matplotlib.colors.rbg_to_hsv 时,它似乎改为输出值 [0-1, 0-1, 0-360]。但是,我在image like this 上使用了这个函数,它似乎以正确的顺序 [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

【问题讨论】:

    标签: python numpy matplotlib scipy


    【解决方案1】:

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

    print colors.rgb_to_hsv(image / 255)
    

    【讨论】:

    • 感谢 Jaime 可能已经解决了它。你知道为什么 H 显示为 0-1 而不是 0-360 之间的值吗?
    • 将色彩空间的每个组件标准化为0-1 是一种合理的约定,可以合法地采用。由于 matplotlib 使用 RGB 颜色空间执行此操作,因此使用 HSV 颜色空间执行此操作是一致的。
    • 请注意,图像必须是 dtype float 以便除以 255 有效。
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2023-03-06
      • 2016-04-14
      • 1970-01-01
      • 2016-09-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-11
      • 2021-07-09
      相关资源
      最近更新 更多