Super Cool Bucket
Super Cool Bucket

Reputation: 33

Not getting correct subtraction result for difference of two images in python

This is my python code where i want to find difference between two images.

import cv
import numpy as np
img1=cv.imread('/storage/emulated/0/a.jpg',0)
print(img1[0:1])
img2=img1
img2[0:1994]=1
print(img2[0:1])
rows,cols=img1[0:1].shape
print(rows)
print(cols)
rows,cols=img2[0:1].shape
print(rows)
print(cols)
print(np.subtract(img1[0:1,0:1], img2[0:1,0:1]))

I am subtracting these numpy arrays but getting zero always. Kindly help regarding this matter.

Upvotes: 0

Views: 209

Answers (1)

Jeru Luke
Jeru Luke

Reputation: 21203

The problem lies in the way you have copied the image.

When you assign an object using the assignment operator (=), the changes made on one object will be reflected in the other image as well. So your this case when you do img2 = img1 the changes made in img2 are reflected in img1 also. Hence upon subtraction you are getting zero always.

A quick fix would be to use copy() method. This creates a new object img2 all together. Hence changes made in img2 will not be reflected in img1 and vice-versa.

img2 = img1.copy() 

Now printing print(np.subtract(img1[0:1,0:1], img2[0:1,0:1])) yields me [[233]]

Have look at THIS BLOG POST also.

Upvotes: 1

Related Questions