RJ Uy
RJ Uy

Reputation: 397

Compare two images if they have almost identical RGB color distribution

I have two colored images img1 and img2 as defined below

 img1 = cv2.imread("source1")
 img2 = cv2.imread("source2")

Now I want to know if the distribution of the RGB value of two images is almost identical. As a human, I can see from the RGB histogram distribution of the two images that they are almost identical or not. But is there a way that I can do this via OpenCV, that it can tell that two images are almost identical with it comes to its RGB distribution?

color = ('b','g','r')
for i,col in enumerate(color):
   histr = cv.calcHist([img1],[i],None,[256],[0,256])
   plt.subplot(1,2,1)
   plt.plot(histr,color = col)
   plt.xlim([0,256])
   plt.title("Img 1")

   histr = cv.calcHist([img2],[i],None,[256],[0,256])
   plt.subplot(1,2,2)
   plt.plot(histr,color = col)
   plt.xlim([0,256])
   plt.title("Img 2")
plt.show()

Upvotes: 3

Views: 1884

Answers (2)

fmw42
fmw42

Reputation: 53081

You can use cv2.compareHist() in Python/OpenCV. It takes two histograms that can be 1D, 2D or 3D histograms and returns a metric score of similarity.

See https://docs.opencv.org/3.4/d6/dc7/group__imgproc__hist.html#gaf4190090efa5c47cb367cf97a9a519bd and https://docs.opencv.org/3.4/d8/dc8/tutorial_histogram_comparison.html and https://www.pyimagesearch.com/2014/07/14/3-ways-compare-histograms-using-opencv-python/, for example

Upvotes: 1

Mark Setchell
Mark Setchell

Reputation: 207445

If you take each point on the x-axis of the two histograms A and B, then the amount of overlap between the two at that point is the height of the smaller:

min(A,B)

So, you just need to sum over the points:

np.sum(np.minimum(A,B))

As an empirical explanation, if both histograms are tall in the same places, the histogram overlap will be high, as will min(A,B). If one is high and one is low, the histogram overlap and min(A,B) will be low.

I found a nice illustration here which usefully also suggests normalisation by dividing by the total number of pixels.

Upvotes: 1

Related Questions