5
$\begingroup$

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.

$\endgroup$
  • $\begingroup$ check this link it works perfectly blenderartists.org/forum/… $\endgroup$ – Jalouse Dec 27 '17 at 9:53
  • $\begingroup$ This helped me: blender.stackexchange.com/questions/72052/… $\endgroup$ – Justin Helps Apr 24 '18 at 15:37
  • $\begingroup$ @JustinHelps That is based on nodes. The code I have answered below does the same thing $\endgroup$ – Akash Hamirwasia Apr 24 '18 at 19:45
  • $\begingroup$ 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. $\endgroup$ – Justin Helps Apr 24 '18 at 22:26
  • $\begingroup$ @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. $\endgroup$ – Akash Hamirwasia Apr 25 '18 at 8:05
4
$\begingroup$

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

$\endgroup$
  • $\begingroup$ It definitely helps, but in my case the values are still slightly off. I tried tuning the Gamma value, but no luck. $\endgroup$ – unfa May 26 '17 at 13:15
  • 1
    $\begingroup$ 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 $\endgroup$ – Akash Hamirwasia May 29 '17 at 12:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.