Skip to content

Instantly share code, notes, and snippets.

@gonzalo123
Created April 17, 2017 16:08
Show Gist options
  • Save gonzalo123/df3e43477f8627ecd1494d138eae03ae to your computer and use it in GitHub Desktop.
Save gonzalo123/df3e43477f8627ecd1494d138eae03ae to your computer and use it in GitHub Desktop.
compare images with opencv
import cv2
import numpy as np
from skimage.measure import compare_ssim as ssim
def mse(imageA, imageB):
# the 'Mean Squared Error' between the two images is the
# sum of the squared difference between the two images;
# NOTE: the two images must have the same dimension
err = np.sum((imageA.astype("float") - imageB.astype("float")) ** 2)
err /= float(imageA.shape[0] * imageA.shape[1])
# return the MSE, the lower the error, the more "similar"
# the two images are
def diff_remove_bg(img0, img, img1):
d1 = diff(img0, img)
d2 = diff(img, img1)
return cv2.bitwise_and(d1, d2)
x1 = cv2.imread("images/xx1.jpg")
x2 = cv2.imread("images/xx12.jpg")
x1 = cv2.cvtColor(x1, cv2.COLOR_BGR2GRAY)
x2 = cv2.cvtColor(x2, cv2.COLOR_BGR2GRAY)
absdiff = cv2.absdiff(x1, x2)
cv2.imwrite("images/absdiff.png", absdiff)
diff = cv2.subtract(x1, x2)
result = not np.any(diff)
m = mse(x1, x2)
s = ssim(x1, x2)
print "mse: %s, ssim: %s" % (m, s)
if result:
print "The images are the same"
else:
cv2.imwrite("images/diff.png", diff)
print "The images are different"
@harishalpha
Copy link

Hi Arvinder,

Please add your two input folders path here:
x1 = cv2.imread("images/xx1.jpg")
x2 = cv2.imread("images/xx12.jpg")

Also, add your output folder path here:
cv2.imwrite("images/absdiff.png", absdiff)
cv2.imwrite("images/diff.png", diff)

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