使用格式运算符%将numpy的RGB值数组转换为十六进制 [英] Convert numpy array of RGB values to hex using format operator %

查看:132
本文介绍了使用格式运算符%将numpy的RGB值数组转换为十六进制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

遵循此SO 问题使用格式化运算符将其应用于numpy数组的最佳方法是什么,该数组的格式如下所示,对应于RGB值

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

请注意,RGB值已从0缩放到1,因此乘以255即可重新缩放

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

,您需要为每行十六进制三元组

推荐答案

您可以使用matplotlib中的rgb2hex.

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

如果您不希望使用matplotlib函数,则需要在使用引用的SO答案之前将数组转换为int.请注意,我认为输出中会有一些细微差异,这是由于四舍五入误差所致.

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

这篇关于使用格式运算符%将numpy的RGB值数组转换为十六进制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆