New covers.
[librarian.git] / src / librarian / covers / utils / color.py
1 def luminance(rgb):
2     rgb = [
3         c / 255 
4         for c in rgb
5     ]
6     rgb = [
7         c / 12.92 if c < .03928 else ((c + .055) / 1.055) ** 2.4
8         for c in rgb
9     ]
10     return .2126 * rgb[0] + .7152 * rgb[1] + .0722 * rgb[2]
11
12
13 def cdist(a, b):
14     d = abs(a-b)
15     if d > 128:
16         d = 256 - d
17     return d
18
19
20 def algo_contrast_or_hue(img, colors):
21     rgb = img.convert('RGB').resize((1, 1)).getpixel((0, 0))
22     lumi = luminance(rgb)
23
24     if lumi > .9:
25         return colors[3]
26     elif lumi < .1:
27         return colors[2]
28
29     hue = img.convert('HSV').resize((1, 1)).getpixel((0, 0))[0]
30     return max(
31         colors[:3],
32         key=lambda c: cdist(hue, c['hsv'][0]) ** 2 + (lumi - c['luminance']) ** 2
33     )
34
35
36 def is_very_bright(img):
37     rgb = img.convert('RGB').getpixel((0, 0))
38     lumi = luminance(rgb)
39     return lumi > .95