Skip to content

Instantly share code, notes, and snippets.

@astanin
Created October 14, 2010 15:20
Show Gist options
  • Save astanin/626356 to your computer and use it in GitHub Desktop.
Save astanin/626356 to your computer and use it in GitHub Desktop.
Compare two aligned images of the same size
#!/usr/bin/env python
"""Compare two aligned images of the same size.
Usage: python compare.py first-image second-image
"""
import sys
from scipy.misc import imread
from scipy.linalg import norm
from scipy import sum, average
def main():
file1, file2 = sys.argv[1:1+2]
# read images as 2D arrays (convert to grayscale for simplicity)
img1 = to_grayscale(imread(file1).astype(float))
img2 = to_grayscale(imread(file2).astype(float))
# compare
n_m, n_0 = compare_images(img1, img2)
print "Manhattan norm:", n_m, "/ per pixel:", n_m/img1.size
print "Zero norm:", n_0, "/ per pixel:", n_0*1.0/img1.size
def compare_images(img1, img2):
# normalize to compensate for exposure difference
img1 = normalize(img1)
img2 = normalize(img2)
# calculate the difference and its norms
diff = img1 - img2 # elementwise for scipy arrays
m_norm = sum(abs(diff)) # Manhattan norm
z_norm = norm(diff.ravel(), 0) # Zero norm
return (m_norm, z_norm)
def to_grayscale(arr):
"If arr is a color image (3D array), convert it to grayscale (2D array)."
if len(arr.shape) == 3:
return average(arr, -1) # average over the last axis (color channels)
else:
return arr
def normalize(arr):
rng = arr.max()-arr.min()
amin = arr.min()
return (arr-amin)*255/rng
if __name__ == "__main__":
main()
@haisi
Copy link

haisi commented Apr 24, 2018

rng can be 0 which leads to all kinds of problems. It should be:

def normalize(arr):
    rng = arr.max()-arr.min()
    if rng == 0:
        rng = 1
    amin = arr.min()
    return (arr-amin)*255/rng

@Shanthika
Copy link

Hello, I've got this after running the python code can you please explain to me what i can infer from this?
please I'm really in need of this....

(tfgpu) mllab@admin-HP:~/Desktop/VinayV/darknet/image comparision$ python3 compare.py equirectangular.png equirectangular1.png
Manhattan norm: 189937836.75 / per pixel: 90.5694183111
Zero norm: 2090691.0 / per pixel: 0.996919155121

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment