# Properly convert Hex Color code to Blender RGB in python

I have noticed that a color can be assigned, by their rgb values in Blender using Python. But it is not possible to directly assign a hex color code to it.

Also, there were some hex to rgb function which I found and used, but still it does not give the correct rgb values because Blender uses 'Gamma Corrected' color values.

Hence, I have found out a proper way to convert hex color code to RGB Color Value.

• check this link it works perfectly blenderartists.org/forum/… – Jalouse Dec 27 '17 at 9:53
• This helped me: blender.stackexchange.com/questions/72052/… – Justin Helps Apr 24 '18 at 15:37
• @JustinHelps That is based on nodes. The code I have answered below does the same thing – Akash Hamirwasia Apr 24 '18 at 19:45
• There is also an extra bit in the bottom answer to that question which talks about setting color management to "Raw". This turns off the gamma correction, allowing people to get the desired colors even if their gamma isn't 2.2, which seems to be the case for some folks in these threads. – Justin Helps Apr 24 '18 at 22:26
• @JustinHelps Yes, but actually that is not a good practice. Gamma correction is followed in all softwares and explicitly disabling it would not give correct colors in renders. – Akash Hamirwasia Apr 25 '18 at 8:05

This can be achieved using the following code:

def hex_to_rgb(value):
gamma = 2.2
value = value.lstrip('#')
lv = len(value)
fin = list(int(value[i:i + lv // 3], 16) for i in range(0, lv, lv // 3))
r = pow(fin[0] / 255, gamma)
g = pow(fin[1] / 255, gamma)
b = pow(fin[2] / 255, gamma)
fin.clear()
fin.append(r)
fin.append(g)
fin.append(b)
fin.append(1.0)
return tuple(fin)


It may not be completely clean code, but is really helpful

• It definitely helps, but in my case the values are still slightly off. I tried tuning the Gamma value, but no luck. – unfa May 26 '17 at 13:15
• The above method is not 100% accurate, and that is why I have posted it here so that someone can suggest a better method. I think that Gamma should be 2.2 based on Wikipedia: en.wikipedia.org/wiki/Gamma_correction – Akash Hamirwasia May 29 '17 at 12:48
• I apologize but I would like to point out that this is not a precise answer, so it could create problems, the Hex values change, albeit slightly. I think this answer should be reviewed – Noob Cat Nov 23 '19 at 2:26