cv2 treshold does not work correctly on second image

53 Views Asked by At

I am new to python and I was playing around with background subtraction to visualize changes in pre and post change images.

I wrote a short and simple script using the cv2 library:

#!/usr/bin/env python

import cv2 as cv
import numpy as np
from matplotlib import pyplot as plt


#GRAYSCALE ONLY FOR TESTING
#Test with person appearing in image
img1 = cv.imread("images/1.jpg", 0)
img2 = cv.imread("images/2.jpg", 0)
img3 = cv.subtract(img1, img2)
ret,thresh1 = cv.threshold(img3,90,255,cv.THRESH_BINARY)


#Test with satelite image of japan landslide changes after earthquake 
jl_before = cv.imread("images/japan_earthquake_before.jpg",0)
jl_after = cv.imread("images/japan_earthquake_after.jpg",0)
jl_subtraction = cv.subtract(jl_before, jl_after)
ret,thresh2 = cv.threshold(img3,20,255,cv.THRESH_BINARY)

images = [img1, img2, thresh1, jl_before, jl_after, thresh2]
titles = ["Image1", "Image2", "Changes", "Japan_Before", "Japan_After", "Japan_Changes" ]
for i in range(6):
    plt.subplot(2,3,i+1),plt.imshow(images[i],'gray')
    plt.title(titles[i])
    plt.xticks([]),plt.yticks([])
plt.show()

The result looks like this:

enter image description here

Why is the mask with changes from the first set of images present in the mask of the second set of images?

I used different variables, thresh1 and thresh2.

Any help would be greatly appreciated as I can't seem to find the problem.

1

There are 1 best solutions below

1
On BEST ANSWER

Because you missed a change when copy pasting:

ret,thresh2 = cv.threshold(img3,20,255,cv.THRESH_BINARY)
                           ^^^^