4

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

Community
  • 1
  • 1
mobcdi
  • 1,532
  • 2
  • 28
  • 49
  • `&` is not a formatting operator. Do you mean `%`? Also, can you given an example of what you want the output to look like? I don't understand what you are asking. – mprat Mar 24 '17 at 13:58
  • Corrected and updated my question – mobcdi Mar 24 '17 at 15:31

1 Answers1

9

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']
Niklas
  • 1,280
  • 1
  • 10
  • 14
  • Hi @Niklas could you explain whats happening in the code you use `[ rgb2hex(*B[i,:]) for i in range(B.shape[0]) ]` – mobcdi Mar 25 '17 at 08:30
  • 2
    Sure. The outer ```[ ]``` brackets denote a [list comprehension](https://docs.python.org/3.6/tutorial/datastructures.html#list-comprehensions). This loops over ```range``` and creates an element for each pass (check ```[ i for i in range(4) ]```). In each pass, one row of ```B```, i.e. ```B[:,i]``` is used as input for the function ```rgb2hex```. Since this function expects three inputs, the ```*``` expands the row which would be one single argument otherwise (see e.g. [this](http://stackoverflow.com/a/1993732/1922650) SO question). – Niklas Mar 25 '17 at 08:57