[英]Convert numpy array of RGB values to hex using format operator %
关于这个SO 问题 ,使用格式化运算符将其应用于numpy数组的最佳方法是什么,其中数组的格式为下面给出的RGB值对应的格式
注意RGB值已经缩放为0到1,因此需要多次255来重新缩放
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
。
from matplotlib.colors import rgb2hex
[ rgb2hex(A[i,:]) for i in range(A.shape[0]) ]
# ['#687847', '#979b8d', '#706d59', '#6a734d', '#8b5e66', '#5e5051']
如果您不想使用matplotlib函数,则需要在使用引用的SO答案之前将数组转换为int
。 请注意,输出略有不同,我认为是由于舍入误差。
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']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.