Differentiate images in python - get a ratio or percentage difference, and generate a diff image
Branch: master
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Type Name Latest commit message Commit time
Failed to load latest commit information.
diffimg fix bug when using on command line Oct 11, 2018
images update readme with png as default + ratio fixes Sep 20, 2018
LICENSE.txt structure how pypi wants Dec 22, 2017
README.md fix link to diff() source in readme Sep 20, 2018
setup.cfg setup for pypi Dec 22, 2017
setup.py update tag Oct 11, 2018
test.py fix ratio calculation Sep 20, 2018



Get the % difference in images using PIL's histogram + generate a diff image. Images should be the same size and have the same color channels (for example, RGB vs RGBA).

PyPI version


Now available from PyPi: pip install diffimg


>>> from diffimg import diff
>>> diff('mario-circle-cs.png', 'mario-circle-node.png')

The very simple diff function returns a raw ratio instead of a % by default.


im1_file, im2_file: filenames of images to diff.

delete_diff_file: a fill showing the differing areas of the two images is generated in order to measure the diff ratio. Setting this to True removes it after calculating the ratio.

diff_img_file: filename for the diff image file. Defaults to diff_img.png (regardless of inputed file's types).

As command line tool

python -m diffimg image1 image2 [-r/--ratio] [-d/--delete] [-f/--filename DIFF_IMG_FILE]

--ratio outputs a number between 0 and 1 instead of the default Images differ by X%.

--delete removes the diff file after retrieving ratio/percentage.

--filename specifies a filename to save the diff image under. Must use a valid extension.


$ ./test.py
Ran 6 tests in 0.320s



The difference is defined by the average % difference between each of the channels (R,G,B,A?) at each pair of pixels Axy, Bxy at the same coordinates in each of the two images (why they need to be the same size), averaged over all pairs of pixels.

For example, compare two 1x1 images A and B (a trivial example, >1 pixels would have another step to find the average of all pixels):

A1,1 = RGB(255,0,0) (pure red)

B1,1 = RGB(100,0,0) (dark red)

((255-100)/255 + (0/0)/255 + (0/0)/255))/3 = (155/255)/3 = 0.202614379

So these two 1x1 images differ by 20.2614379% according to this formula.

Sample image 1

Alt text

Sample image 2

Alt text

Resulting diff image

Alt text

Difference percentage output

Images differ by 0.731961813597%