Created
April 4, 2020 21:47
-
-
Save kerel-fs/ca40906edf570896a3bb603083387fe3 to your computer and use it in GitHub Desktop.
Calculate the color temperature CCT from web color hex triplets (Python)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
import struct | |
import warnings | |
import colour | |
import numpy as np | |
measured_colours = ["#E42024", | |
"#E11E22", | |
"#E52125", | |
"#E51E21", | |
"#D71D1E"] | |
# NOTE: The fake scaling factor is BS, | |
# but helps with colours far from the black-body curve | |
fake_scaling_factor = 100 | |
def hex2rgb(hex): | |
# https://stackoverflow.com/a/4296263 | |
rgb_tuple = struct.unpack('BBB', bytes.fromhex(hex[1:])) | |
return np.array(rgb_tuple) | |
def rgb_frac2cct(rgb_frac): | |
# https://stackoverflow.com/a/38889696 | |
xyz = colour.sRGB_to_XYZ(rgb_frac) | |
xy = colour.XYZ_to_xy(xyz) | |
return colour.xy_to_CCT(xy, 'hernandez1999') | |
if __name__ == "__main__": | |
temperatures = [] | |
for color_str in measured_colours: | |
rgb = hex2rgb(color_str) | |
rgb_frac = rgb / 255 / fake_scaling_factor | |
cct = rgb_frac2cct(rgb_frac) | |
temperatures.append(cct) | |
# print('{}\t{}\t{:.1f}'.format(rgb, rgb_frac, cct)) | |
print('{:.0f} +- {:.0f} K'.format(np.mean(temperatures), | |
np.std(temperatures) / np.sqrt(np.std(temperatures)))) | |
# Output: 1074 +- 7 K |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
colour-science~=0.3.15 | |
numpy~=1.18.2 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment