Skip to content

Instantly share code, notes, and snippets.

@hamid814
Created January 5, 2022 12:19
Show Gist options
  • Save hamid814/936016b78476676214b8bd9ab9a1cefa to your computer and use it in GitHub Desktop.
Save hamid814/936016b78476676214b8bd9ab9a1cefa to your computer and use it in GitHub Desktop.
get contrast between two colors ( rgb )
from math import pow
def x(v):
v /= 255
res = v / 12.92 if v <= 0.03928 else pow( (v + 0.055) / 1.055, 2.4 )
return res
def luminance(r, g, b):
a = [x(v) for v in [r, g, b]]
return a[0] * 0.2126 + a[1] * 0.7152 + a[2] * 0.0722
def get_contrast(rgb1, rgb2):
lum1 = luminance(rgb1[0], rgb1[1], rgb1[2])
lum2 = luminance(rgb2[0], rgb2[1], rgb2[2])
brightest = max(lum1, lum2)
darkest = min(lum1, lum2)
return (brightest + 0.05) / (darkest + 0.05)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment