Skip to content

Instantly share code, notes, and snippets.

@limitedeternity
Created December 1, 2018 09:49
Show Gist options
  • Save limitedeternity/6b5deca0a2011b8ea8f04af1b2b28a9a to your computer and use it in GitHub Desktop.
Save limitedeternity/6b5deca0a2011b8ea8f04af1b2b28a9a to your computer and use it in GitHub Desktop.
Automatic solution for "find 10 differences in two pictures" tasks
from skimage.measure import compare_ssim
import argparse
import imutils
import cv2
def are_equal(imageA, imageB):
if imageA.shape == imageB.shape:
difference = cv2.subtract(imageA, imageB)
(b, g, r) = cv2.split(difference)
if cv2.countNonZero(b) == 0 and cv2.countNonZero(g) == 0 and cv2.countNonZero(r) == 0:
return True
else:
return False
else:
return False
def display_diffs(imageA, imageB):
grayA = cv2.cvtColor(imageA, cv2.COLOR_BGR2GRAY)
grayB = cv2.cvtColor(imageB, cv2.COLOR_BGR2GRAY)
(score, diff) = compare_ssim(grayA, grayB, full=True)
diff = (diff * 255).astype("uint8")
threshold = cv2.threshold(diff, 0, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)[1]
cnts = cv2.findContours(threshold.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if imutils.is_cv2() else cnts[1]
for c in cnts:
(x, y, w, h) = cv2.boundingRect(c)
cv2.rectangle(imageA, (x, y), (x + w, y + h), (0, 0, 255), 2)
cv2.rectangle(imageB, (x, y), (x + w, y + h), (0, 0, 255), 2)
cv2.imshow("ImageA", imageA)
cv2.imshow("ImageB", imageB)
cv2.waitKey(0)
return cv2.destroyAllWindows()
if __name__ == "__main__":
ap = argparse.ArgumentParser()
ap.add_argument("-f", "--first", required=True, help="First image")
ap.add_argument("-s", "--second", required=True, help="Second image")
args = vars(ap.parse_args())
imageA = cv2.imread(args["first"])
imageB = cv2.imread(args["second"])
print("Images are completely equal") if are_equal(imageA, imageB) else display_diffs(imageA, imageB)
scikit-image
imutils
opencv-python
@limitedeternity
Copy link
Author

screenshot_1

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