我尝试将图像转换为 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 值转换为 float 或像这样修补函数:
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
关于python - hsv_to_rgb 不是 matplotlib 上 rgb_to_hsv 的倒数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19732270/