JesseJ
JesseJ

Reputation: 65

Detect and count number of different pixels between two images with OpenCV Python

Similar to the question here but I'd like to return a count of the total number of different pixels between the two images.

I'm sure it is doable with OpenCV in Python but I'm not sure where to start.

Upvotes: 1

Views: 4531

Answers (3)

kuzand
kuzand

Reputation: 9806

Assuming that the size of two images is the same

import  numpy as np
import cv2

im1 = cv2.imread("im1.jpg")
im2 = cv2.imread("im2.jpg")

# total number of different pixels between im1 and im2
np.sum(im1 != im2)

Upvotes: 9

Lucas Wiman
Lucas Wiman

Reputation: 11247

Since cv2 images are just numpy arrays of shape (height, width, num_color_dimensions) for color images, and (height, width) for black and white images, this is easy to do with ordinary numpy operations. For black/white images, we sum the number of differing pixels:

(img1 != img2).sum()

(Note that True=1 and False=0, so we can sum the array to get the number of True elements.)

For color images, we want to find all pixels where any of the components of the color differ, so we first perform a check if any of the components differ along that axis (axis=2, since the shape components are zero-indexed):

(img1 != img2).any(axis=2).sum()

Upvotes: 1

Roqux
Roqux

Reputation: 618

You can use openCVs absDiff to get the difference between the images, then countNonZero to get the number of differing pixels.

img1 = cv2.imread('img1.png')
img2 = cv2.imread('img2.png')

difference = cv2.absdiff(img1, img2)

num_diff = cv2.countNonZero(difference)

Upvotes: 5

Related Questions