Thursday, February 16, 2017

Compare two images: the histogram method.

This is a very simple example about how to compare the histograms of both images and print the inconsistencies are bound to arise.
The example come with alternative solution: Histogram method.
The script was run under Fedora 25.
If the images are the same the result will be 0.0.
For testing I change the image2.png by make a line into this with a coverage of 10%.
The result of the script was:
The images come with this dimensions: 738 x 502 px.
import math
import operator
from math import *
import PIL

from PIL import Image
h1 ="image1.png").histogram()
h2 ="image2.png").histogram()

rms = math.sqrt(reduce(operator.add,
        map(lambda a,b: (a-b)**2, h1, h2))/len(h1))
print rms
About the operator module exports a set of efficient functions corresponding to the intrinsic operators of Python.
Example:, b)
operator.le(a, b)
operator.eq(a, b), b), b), b)
operator.__lt__(a, b)
operator.__le__(a, b)
operator.__eq__(a, b)
operator.__ne__(a, b)
operator.__ge__(a, b)
operator.__gt__(a, b)

This is like math operators:
lt(a, b) is equivalent to a < b
le(a, b) is equivalent to a <= b
Another example:
>>> # Elementwise multiplication
>>> map(mul, [0, 1, 2, 3], [10, 20, 30, 40])
[0, 20, 60, 120]

>>> # Dot product
>>> sum(map(mul, [0, 1, 2, 3], [10, 20, 30, 40]))