![](/img/trans.png)
[英]matplotlib colors rgb_to_hsv not working right . Maybe need to report it?
[英]hsv_to_rgb isn't the inverse of rgb_to_hsv on matplotlib
我試圖將圖像轉換為hsv並返回到rgb,但不知怎的,我丟失了顏色信息。
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
而且我也在shell上復制了這個問題,只是在導入后寫這行也會得到相同的結果。
plt.imshow(
matplotlib.colors.hsv_to_rgb(
matplotlib.colors.rgb_to_hsv(mpimg.imread('go2.jpg'))
)
)
你能告訴我我做錯了什么嗎?
請參閱https://github.com/matplotlib/matplotlib/pull/2569上的討論
這是一個整數除法問題。 numpy
認真對待它的類型,似乎不尊重from __future__ import division
。 簡單的解決方法是在調用rgb_to_hsv
之前將rgb值轉換為浮點數或者將函數修改為:
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)
"""
arr = arr.astype('float') # <- add this line
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
這個問題對我來說是可重現的(matplotlib 1.3.0)。 對我來說這看起來像個錯誤。 問題似乎是在rgb_to_hsv
步驟中,飽和度降至零。 至少對於大多數顏色:
import numpy as np
darkgreen = np.array([[[0, 100, 0]]], dtype='uint8')
matplotlib.colors.rgb_to_hsv(darkgreen) # [0.33, 1., 100.], okay so far
darkgreen2 = np.array([[[10, 100, 10]]], dtype='uint8') # very similar colour
matplotlib.colors.rgb_to_hsv(darkgreen2) # [0.33, 0., 100.], S=0 means this is a shade of gray
我認為報告錯誤的正確位置是在github 問題跟蹤器上 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.