RIYA
RIYA

Reputation: 1

IndexError in finding the pixel difference of two images

This following is code using opencv in python to find the pixel difference of two images of the same size. However, it gives me an error in the last line and I don't know how to fix it.

if h1==h2:
    if w1==w2:
        c=np.zeros((h1,w1,3),np.uint8)
        for i in range(img1.shape[0]):
            for j in range(img1.shape[1]):
                c[j][i]=img1[j][i]-img2[j][i]

IndexError: index 480 is out of bounds for axis 0 with size 480

Upvotes: 0

Views: 108

Answers (1)

Reti43
Reti43

Reputation: 9796

You mixed up the indices; i belongs to img1.shape[0].

img1[j][i]-img2[j][i]

That said, numpy can vectorise this process for you and you can simply do

if img1.shape == img2.shape:
    c = img1 - img2

However, you have to be careful with your data type. What if the pixel in one image is 0 and in the other is 32?

>>> np.uint8(0) - np.uint8(32)

Warning (from warnings module):
  File "__main__", line 2
RuntimeWarning: overflow encountered in ubyte_scalars
224

You want to convert them to integers for the difference and if you want to keep the difference in the range 0-255, you can take the absolute of that.

c = img1.astype(int) - img2.astype(int)
# you can optionally do the following depending on what you want to do next
c = np.abs(c).astype(np.uint8)

OpenCV says a function that achieves all that for you, cv2.absdiff().

c = cv2.absdiff(img1, img2)

Upvotes: 1

Related Questions