utd*_*mir 6 python image-processing matplotlib
我试图将图像转换为hsv并返回到rgb,但不知怎的,我丢失了颜色信息.
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
Run Code Online (Sandbox Code Playgroud)

而且我也在shell上复制了这个问题,只是在导入后写这行也会得到相同的结果.
plt.imshow(
matplotlib.colors.hsv_to_rgb(
matplotlib.colors.rgb_to_hsv(mpimg.imread('go2.jpg'))
)
)
Run Code Online (Sandbox Code Playgroud)
你能告诉我我做错了什么吗?
请参阅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
Run Code Online (Sandbox Code Playgroud)