Skip to content

Instantly share code, notes, and snippets.

@jlongman
Created May 11, 2015 21:33
Show Gist options
  • Save jlongman/1d21c1a2fc407d50e553 to your computer and use it in GitHub Desktop.
Save jlongman/1d21c1a2fc407d50e553 to your computer and use it in GitHub Desktop.
A numeric diff of two images
#!/bin/python2.7
from itertools import izip
from PIL import Image
import argparse
import os
parser = argparse.ArgumentParser()
#parser.add_argument("--preserve_case", "-p", action = 'store_true')
# parser.add_argument("--file-list", "-f", action = 'store_true')
parser.add_argument("files", nargs = 2, type = str, default = None)
args = parser.parse_args()
try:
i1 = Image.open(args.files[0])
except Exception as e:
print "error opening LHS " + args.files[0]
raise e
try:
i2 = Image.open(args.files[1])
except Exception as e:
print "error opening RHS " + args.files[1]
raise e
assert i1.mode == i2.mode, "Different kinds of images: " + args.files[0] + " " + args.files[1]
assert i1.size == i2.size, "Different sizes: " + args.files[0] + " " + args.files[1]
pairs = izip(i1.getdata(), i2.getdata())
if len(i1.getbands()) == 1:
# for gray-scale jpegs
dif = sum(abs(p1 - p2) for p1, p2 in pairs)
else:
dif = sum(abs(c1 - c2) for p1, p2 in pairs for c1, c2 in zip(p1, p2))
ncomponents = i1.size[0] * i1.size[1] * 3
print "Difference (percentage) Pixels: {:>6.1%}".format((dif / 255.0) / ncomponents),
statinfo = os.stat(args.files[0])
i1size = statinfo.st_size
statinfo = os.stat(args.files[1])
i2size = statinfo.st_size
print " Size: {:>6.1%} ".format(float(i2size) / i1size),
print args.files[0]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment