1
def images_the_same(image1, image2):
    """
    :param image1: path of image1
    :param image2: path of image2
    :return: True if images are the same, False if images are not the same
    """
    im1 = cv.imread(image1)
    im2 = cv.imread(image2)

    if im1.shape != im2.shape:
        return False

    difference = cv.subtract(im1, im2)
    b, g, r = cv.split(difference)

    if cv.countNonZero(b) == 0 and cv.countNonZero(g) == 0 and cv.countNonZero(r) == 0:
        return True
    return False
print(images_the_same('cards/firstone.png', 'current_card.png'))  # result = True
print(images_the_same('current_card.png', 'cards/firstone.png'))  # result = False

How is it possible that the results are different for the first function call, while the second function call with different order shows a different result? It worked fine a few days ago. Is there something missing here? Is the function not implemented correctly?

alexia
  • 14,440
  • 8
  • 42
  • 52
agronom
  • 11
  • 1
  • Can you state your opencv version as it would help in debugging – Ibrahim Sherif Aug 22 '21 at 10:05
  • it is opencv 4.5.3 – agronom Aug 22 '21 at 10:23
  • Try to use cv2, not cv Try to check your pictures. Your code is good – Nurislom Rakhmatullaev Aug 22 '21 at 09:59
  • images are the same sizes but otherwise completely different. i changed code to cv2 and there is still the same result. it really worked fine few days ago, but now not anymore. i also thought about library update but as i searched last update was in july.. – agronom Aug 22 '21 at 10:27
  • 4
    [`cv::subtract`](https://docs.opencv.org/4.5.2/d2/de8/group__core__array.html#gaa0f00d98b4b5edeaeb7b8333b2de353b) saturates, so rather than testing for equality, you're testing for less-or-equal. Use [`cv::absDiff`](https://docs.opencv.org/4.5.2/d2/de8/group__core__array.html#ga6fef31bc8c4071cbc114a758a2b79c14) instead. | The split is wasteful, since it will allocate 3 new arrays -- instead, just reshape the image to single channel and do a single `countNonZero` on the result. – Dan Mašek Aug 22 '21 at 11:49
  • 3
    instead of countnonzero, just use numpy and say `(difference == 0).all()` – Christoph Rackwitz Aug 22 '21 at 12:57
  • 3
    Or better yet, just do `(im1 == im2).all()`. No point in computing differences if you only compare them to 0. – Cris Luengo Aug 22 '21 at 14:38

0 Answers0