Search code examples
pythonnumpyopencvpython-imaging-libraryscikit-image

How to find the difference of images in numpy arrays?


I'm trying to calculate the difference between 2 images. I'm expecting an integer as my result, but I'm not getting what I expect.

from imageio import imread
#https://raw.githubusercontent.com/glennford49/sampleImages/main/cat1.png
#https://raw.githubusercontent.com/glennford49/sampleImages/main/cat2.png
img1="cat1.png" # 183X276
img2="cat2.png" # 183x276
numpyImg1=[]
numpyImg2=[]
img1=imread(img1)
img2=imread(img2)
numpyImg1.append(img1)
numpyImg2.append(img2)
diff = numpyImg1[0] - numpyImg2[0] 
result = sum(abs(diff)) 

print("difference:",result)

print:

# it prints an array of images rather than printing an interger only

target:

difference: <int>

Solution

  • This is my answer of finding the difference of 2 images in rgb channels.

    If 2 the same images were to be subtracted, prints: difference per pixel: 0

    from numpy import sum
    from imageio import imread
    
    #https://github.com/glennford49/sampleImages/blob/main/cat2.png
    #https://github.com/glennford49/sampleImages/blob/main/cat2.png
    img1="cat1.png"
    img2="cat2.png"
    numpyImg1=[]
    numpyImg2=[]
    img1=imread(img1)
    img2=imread(img2)
    numpyImg1.append(img1)
    numpyImg2.append(img2)
    diff = numpyImg1[0] - numpyImg2[0] 
    result = sum(diff/numpyImg1[0].size)
    result = sum(abs(result.reshape(-1))) 
    print("difference per pixel:",result)