mobcdi
mobcdi

Reputation: 1592

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

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

Upvotes: 4

Views: 9503

Answers (1)

Niklas
Niklas

Reputation: 1360

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

Upvotes: 9

Related Questions