0

l would like to convert my array of colors to RGB pixel values .

colors

array(['#32CD32', '#CD5C5C', '#00BFFF', '#1E90FF', '#00008B', '#ADFF2F',
       '#B0E0E6', '#7CFC00', '#00008B', '#1E90FF', '#F08080', '#F08080',
       '#FA8072', '#0000FF', '#7CFC00', '#B0E0E6'],
      dtype='<U7')

What l have tried ?

pixel_color = ['#%02x%02x%02x' % (c[0], c[1], c[2]) for c in colors]

l got the following error :

***** TypeError: %x format: an integer is required, not str**

Then l did the following :

pixel_color = ["#%02x%02x%02x" %(int(c[0]), int(c[1]), int(c[2])) for c in colors]

Then l get the following error :

***** ValueError: invalid literal for int() with base 10: '#'**

user3483203
  • 50,081
  • 9
  • 65
  • 94
eric lardon
  • 351
  • 1
  • 6
  • 21
  • Possible duplicate of [Converting Hex to RGB value in Python](https://stackoverflow.com/questions/29643352/converting-hex-to-rgb-value-in-python) – user3483203 Mar 30 '18 at 10:31
  • Hi @chrisz, thank you for your comment l tried that pixel_color = ["%02x%02x%02x" %(int(c[0]), int(c[1]), int(c[2])) for c in colors] however l get the same error ValueError: invalid literal for int() with base 10: '#' – eric lardon Mar 30 '18 at 10:33
  • Yea because you aren't stripping the `#` from your input – user3483203 Mar 30 '18 at 10:33
  • colors= [c.strip('#') for c in colors] which returns ['32CD32', 'CD5C5C', '00BFFF', '1E90FF', '00008B', 'ADFF2F', 'B0E0E6', '7CFC00', '00008B', '1E90FF', 'F08080', 'F08080', 'FA8072', '0000FF', '7CFC00', 'B0E0E6'] then pixel_color = ["%02x%02x%02x" %(int(c[0]), int(c[1]), int(c[2])) for c in colors] *** ValueError: invalid literal for int() with base 10: 'C – eric lardon Mar 30 '18 at 10:38
  • I'm not sure what you are expecting that code to do. – user3483203 Mar 30 '18 at 10:38

1 Answers1

1

You aren't stripping the # from your input before you try the conversion. Also, why don't you just use bytes.fromhex():

x = ['#32CD32', '#CD5C5C', '#00BFFF', '#1E90FF', '#00008B', '#ADFF2F',
'#B0E0E6', '#7CFC00', '#00008B', '#1E90FF', '#F08080', '#F08080',
'#FA8072', '#0000FF', '#7CFC00', '#B0E0E6']

for i in x:
  red, green, blue = bytes.fromhex(i[1:])
  print(red, green, blue)

Output:

50 205 50
205 92 92
0 191 255
30 144 255
0 0 139
173 255 47
176 224 230
124 252 0
0 0 139
30 144 255
240 128 128
240 128 128
250 128 114
0 0 255
124 252 0
176 224 230
user3483203
  • 50,081
  • 9
  • 65
  • 94
  • 1
    Awesome, this is what l'm looking for. Thank you @chrisz – eric lardon Mar 30 '18 at 10:43
  • 1
    WARNING: `#` prefix say that what follow is a colour code, not a hex number. You should expand it, if the colour string is just 3 (additinal) characters (short code, very common). This should be done before to convert the number. – Giacomo Catenazzi Mar 30 '18 at 15:42