-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathluminosity.py
72 lines (50 loc) · 1.41 KB
/
luminosity.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
from PIL import Image
import sys
def get_brightness(image):
total_brightness = 0
total_pixels = 0
for pixel in get_pixels(image):
brightness = get_pixel_brightness(pixel)
total_brightness += brightness
total_pixels += 1
if total_pixels > 0:
average_brightness = total_brightness / total_pixels
return round(average_brightness, 3)
else:
return 0
def get_pixels(image):
"""Get all non-transparent pixels."""
image = image.convert('RGBA')
pixel_matrix = image.load()
size = image.size
width, height = size
for x in range(0, width):
for y in range(0, height):
pixel = pixel_matrix[x, y]
if not is_transparent(pixel):
yield pixel[:3]
def get_pixel_brightness(pixel):
red, green, blue = pixel
redness = red * 0.2126
greenness = green * 0.7152
blueness = blue * 0.0722
brightness = redness + greenness + blueness
return brightness
def is_transparent(pixel):
if len(pixel) <= 3:
return False
else:
if pixel[3] > 0:
return False
return True
def get_brightest(files):
brightest = None
for path in files:
try:
brightness = get_brightness(path)
except IOError:
continue
entry = (brightness, path)
if entry > brightest:
brightest = entry
return brightest