Search code examples
pythonimageopencvdifferencethreshold

opencv threshold problem for finding diff images


I have 2 images like below. I want to have differences two of them.

I tried some codes with threshold. But no threshold different. two images threshold image is all black. How can I make differences are with color white on thresh?

(the difference is just on top-left like a small dark)

before = cv2.imread('1.png')
after = cv2.imread('2.png')

threshb = cv2.threshold(before, 0, 255, cv2.THRESH_BINARY_INV)[1]
thresha = cv2.threshold(after, 0, 255, cv2.THRESH_BINARY_INV)[1]

cv.imshow("before",threshb)
cv.imshow("after",thresha)

Not: I used "structural_similarity" link here for finding differences but it founds a lot of differences :(

I don't need small pixel differences. I need differences like seen with human eyes.

enter image description here

enter image description here

enter image description here


Solution

  • The way to handle that is to do absdiff followed by some gain in Python/OpenCV. When you do the absdiff with these images, the difference is small so will not be much above black. So you have to increase the gain to see the difference. (Or you could set an appropriate threshold)

    Input 1:

    enter image description here

    Input 2:

    enter image description here

    import cv2
    import numpy as np
    from skimage import exposure as exposure
    
    # read image 1
    img1 = cv2.imread('gray1.png', cv2.IMREAD_GRAYSCALE)
    
    # read image 2
    img2 = cv2.imread('gray2.png', cv2.IMREAD_GRAYSCALE)
    
    # do absdiff
    diff = cv2.absdiff(img1,img2)
    
    # apply gain
    result1 = cv2.multiply(diff, 5)
    
    # or do threshold
    result2 = cv2.threshold(diff, 10, 255, cv2.THRESH_BINARY)[1]
    
    # save result
    cv2.imwrite('gray1_gray2_diff1.png', result1)
    cv2.imwrite('gray1_gray2_diff2.png', result2)
    
    # display result
    cv2.imshow('diff', diff)
    cv2.imshow('result1', result1)
    cv2.imshow('result2', result2)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    

    Result 1 (gain):

    enter image description here

    Result 2 (threshold):

    enter image description here