Home > OS >  compare two images and output their histograms
compare two images and output their histograms

Time:06-04

I have two b&w images that I would like to compare using a histogram.

I am using the following code to display a histogram of a single image:

import cv2
from matplotlib import pyplot as plt
img = plt.imread('222.jpg', 0)
histr = cv2.calcHist([img],[0],None,[256],[0,256])
plt.plot(histr)
plt.show()

I get the output histogram:

enter image description here

Could you tell me please, how do I make it so that two histograms of two b&w images are displayed on the output graph, for example, the first image is displayed with a red line, and the second image with a blue line, well, or any other histogram format. Also, please tell me how I can get the data of my b&w images so that I can build a histogram in excel, for example. Thank you very much!

CodePudding user response:

  1. You need to mention the plots of both the b&w images and then display it

  2. Choose colors using color flag within plot()

Code:

img1 = plt.imread('image_1.jpg', 0)
img2 = plt.imread('image_2.jpg', 0)

# histogram of both images
hist1 = cv2.calcHist([img1],[0],None,[256],[0,256])
hist2 = cv2.calcHist([img2],[0],None,[256],[0,256])

# plot both the histograms and mention colors of your choice
plt.plot(hist1,color='red')
plt.plot(hist2, color='green')

plt.show()

enter image description here

To answer your second question, store the values in hist1 and hist2 as two separate columns in a dataframe. Save the dataframe as an excel or CSV file. You can later open the file, select the columns and plot.

  • Related