hsv_to_rgb不是matplotlib上的rgb_to_hsv的反转 [英] hsv_to_rgb isn't the inverse of rgb_to_hsv on matplotlib
问题描述
我试图将图像转换为hsv并返回rgb,但不知何故我丢失了颜色信息。
I tried to convert an image to hsv and back to rgb, but somehow I lost color information.
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
我也在shell上复制了这个问题,只是在导入后写这一行也会得到相同的结果。
And I also replicated the problem on shell too, just writing this line after importing also gives the same result.
plt.imshow(
matplotlib.colors.hsv_to_rgb(
matplotlib.colors.rgb_to_hsv(mpimg.imread('go2.jpg'))
)
)
你能告诉我我做错了什么吗?
Can you tell me what am I doing wrong?
推荐答案
编辑:这只是一个部分解决方案,
请参阅 https: //github.com/matplotlib/matplotlib/pull/2569
这是一个整数除法问题。 numpy
认真对待它的类型,似乎不尊重来自__future__ import division的
。简单的解决方法是在调用 rgb_to_hsv
之前将rgb值转换为浮点值,或者修改函数:
This is an integer division issue. numpy
is serious about it's types and seems to not respect from __future__ import division
. The simple work around is to convert your rgb values to floats before calling rgb_to_hsv
or patch the function as such:
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
这篇关于hsv_to_rgb不是matplotlib上的rgb_to_hsv的反转的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!