Thursday, August 3, 2017

Python Conversion of Kelvin color temperature to to Hex color code

import math
import numpy as np
import matplotlib.pyplot as plt

#Convert kelvin to HEX code..... 
Temperature = [k for k in range(1000, 4001, 5)]

color=[]
for i in range(len(Temperature)):
    Red = 0
    Green = 0
    Blue = 0
    
    Temp = Temperature[i]/100
    #Calculate Red:
    if Temp <= 66: Red = 255
    else:
        Red = Temp - 60
        Red = 329.698727446 * (Red ** -0.1332047592)
        if Red < 0: Red = 0
        if Red > 255: Red = 255

    #Calculate Green:

    if Temp <= 66:
        Green = Temp
        Green = 99.4708025861 * math.log(Green) - 161.1195681661
        if Green < 0: Green = 0
        if Green > 255: Green = 255
    else:
        Green = Temp - 60
        Green = 288.1221695283 * (Green ** -0.0755148492)
        if Green < 0: Green = 0
        if Green > 255: Green = 255

    #Calculate Blue:

    if Temp >= 66: Blue = 255
    else:
        if Temp <= 19: Blue = 0
        else: 
            Blue = Temp - 10
            Blue = 138.5177312231 * math.log(Blue) - 305.0447927307
            if Blue < 0: Blue = 0
            if Blue > 255: Blue = 255

    color.append('#%02X%02X%02X' % (int(Red),int(Green),int(Blue)))
#    print("HEX code for kelvin", Temperature[i], "is:" ,color[i])  
    
#ploting the color range
fig = plt.figure(figsize=(25,3), dpi=25)
plt.subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=None, hspace=None)

ax = fig.add_subplot(111)
ax.spines['right'].set_visible(False)
ax.spines['left'].set_visible(False)
ax.spines['top'].set_visible(False)
ax.spines['bottom'].set_visible(False)

bottom_00 = [0]*len(Temperature)
bar = ax.bar(np.arange(len(Temperature)), [1]*len(Temperature), width=1, color=color, 
             alpha=1, align='center', bottom=bottom_00)

ax.set_xticks([])
ax.set_xticklabels(labels=[])
ax.set_yticks([])
ax.set_yticklabels(labels=[])
plt.show()

No comments:

Post a Comment