Convert numpy array of RGB values to hex using format operator %

∥☆過路亽.° 提交于 2019-12-07 07:36:06

问题


Following on this SO question what would be the best way to use the formatting operator to apply it to a numpy array where the array is of the format given below corresponding to RGB values

Note RGB values have been scaled 0 to 1 so multiple by 255 to rescale

array([[ 0.40929448,  0.47071505,  0.27701891],
       [ 0.59383913,  0.60611158,  0.55329837],
       [ 0.4393785 ,  0.4276561 ,  0.34999225],
       [ 0.4159481 ,  0.4516056 ,  0.3026519 ],
       [ 0.54449997,  0.36963636,  0.4001209 ],
       [ 0.36970012,  0.3145826 ,  0.315974  ]])

and you want a hex triplet value for each row


回答1:


You can use the rgb2hex from matplotlib.

from matplotlib.colors import rgb2hex

[ rgb2hex(A[i,:]) for i in range(A.shape[0]) ]
# ['#687847', '#979b8d', '#706d59', '#6a734d', '#8b5e66', '#5e5051']

If you would rather not like the matplotlib function, you will need to convert your array to int before using the referenced SO answer. Note that there are slight differences in the output which I assume to be due to rounding errors.

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']


来源:https://stackoverflow.com/questions/43001349/convert-numpy-array-of-rgb-values-to-hex-using-format-operator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!