How can I convert multiple HEX values into HSV values at once?

Viewed 37

I'm using Python to convert colour HEX values into HSV values using the hex2rgb() and rgb2hsv() functions. More info about the code I'm using can be found here: https://codeigo.com/python/convert-hex-to-rgb-and-hsv.

The code works fine for 1 HEX value, but I cannot figure out how you can use this code for multiple HEX values.

Example: print(rgb2hsv(*hex2rgb("#b4a795"))) works and gives me the following output: (35, 17, 71). This is what I need, but how can you use this code if you have a list of multiple HEX values? Let's say HEX values #b4a795, #e7e0d6, #d7cfc8 as an example.

I have to add that I'm new to Python, so this might be a simple solution. In any case, any help is greatly appreciated!

3 Answers

A list comprehension could be helpful here. You can try something like:

hex_values = ['#b4a795', '#e7e0d6', '#d7cfc8']

hsv_values = [rgb2hsv(*hex2rgb(hex_val)) for hex_val in hex_values]

put your hex values in a list, then iterate it.

hexValues = ["#b4a795", "#e7e0d6", "#d7cfc8"]
hsvValues = []
for i in hexValues:
    hsvValues.append(rgb2hsv(*hex2rgb(i)))

print(hsvValues)

You can store your colours into a list and elaborate it with a for loop

def convert_series(color_list):
  my_list = []
  for x in range(0,len(color_list)):
    my_list.append(rgb2hsv(*hex2rgb(color_list[x])))
  return my_list

list_color = ['#b4a795', '#e7e0d6', '#d7cfc8']

print(convert_series(list_color))
new_list = convert_series(list_color)

You can then access to them via new_list[0],new_list[1] etc

I suggest to check Python documentation on for loop and lists/data structures

Related