1

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.

JesseJ
  • 65
  • 1
  • 4
  • You could just try taking the difference between the images and counting the non-zero elements. You can convert the images to numpy arrays and then this becomes trivial. – cmxu Jan 08 '20 at 19:29
  • Welcome to StackOverflow. This site does not serve as general problem solving portal. The community will help you to get a working solution, but you should share your code with images showing what you have done already that did not work. Read "How to create a Minimal, Reproducible Example" (https://stackoverflow.com/help/minimal-reproducible-example), "What are good topics" (https://stackoverflow.com/help/on-topic) and "How do I ask a good question" (https://stackoverflow.com/help/how-to-ask)? – fmw42 Jan 08 '20 at 19:52
  • Obtain a binary mask of each image then bitwise-xor to get the different number of pixels. Then count number of pixels on the resulting mask with `cv2.countNonZero` – nathancy Jan 08 '20 at 20:44
  • _I'm sure it is doable with OpenCV in Python but I'm not sure where to start._ This isn't what Stack Overflow is for, sorry. – AMC Jan 08 '20 at 22:46

3 Answers3

9

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)
Andreas K.
  • 9,282
  • 3
  • 40
  • 45
5

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)
Roqux
  • 608
  • 1
  • 11
  • 25
1

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()
Lucas Wiman
  • 10,021
  • 2
  • 37
  • 41