forked from bokeh/bokeh
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathimage_diff.py
More file actions
38 lines (29 loc) · 1018 Bytes
/
image_diff.py
File metadata and controls
38 lines (29 loc) · 1018 Bytes
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
from PIL import Image, ImageChops
import logging
logging.getLogger('PIL.PngImagePlugin').setLevel(logging.INFO)
def image_diff(diff_path, before_path, after_path, superimpose=False):
""" Returns the percentage of differing pixels or -1 if dimensions differ. """
before = Image.open(before_path)
after = Image.open(after_path)
if before.size != after.size:
return -1
before = before.convert('RGBA')
after = after.convert('RGBA')
mask = ImageChops.difference(before, after)
mask = mask.convert('L')
mask = mask.point(lambda k: 0 if k == 0 else 255)
if mask.getbbox() is None:
return 0
else:
diff = mask.convert('RGB')
if superimpose:
diff.paste(after, mask=mask)
else:
diff.paste((0, 0, 255), mask=mask)
diff.save(diff_path)
w, h = after.size
pixels = 0
for v in mask.getdata():
if v == 255:
pixels += 1
return float(pixels)/(w*h)*100