您可以使用rgb2hex
来自 matplotlib。
from matplotlib.colors import rgb2hex
[ rgb2hex(A[i,:]) for i in range(A.shape[0]) ]
# ['#687847', '#979b8d', '#706d59', '#6a734d', '#8b5e66', '#5e5051']
如果您不想使用 matplotlib 函数,则需要将数组转换为int
在使用引用的 SO 答案之前。请注意,输出存在细微差异,我认为这是由于舍入误差造成的。
B = np.array(A*255, dtype=int) # convert to int
# Define a function for the mapping
rgb2hex = lambda r,g,b: '#%02x%02x%02x' %(r,g,b)
[ rgb2hex(*B[i,:]) for i in range(B.shape[0]) ]
# ['#687846', '#979a8d', '#706d59', '#6a734d', '#8a5e66', '#5e5050']