如何在 OpenCV Python 中绘制图像不同颜色的直方图?
在 OpenCV 中计算直方图,我们使用cv2.calcHist()函数。在本教程中,我们将展示如何计算输入图像不同颜色(蓝色、绿色和红色)的直方图。
要计算和绘制图像不同颜色的直方图,可以按照以下步骤操作:
步骤
导入所需的库OpenCV和matplotlib。确保您已安装它们。
import cv2 import matplotlib.pyplot as plt
使用cv2.imread()方法读取图像。图像的宽度和高度必须相同。
img1 = cv2.imread('birds.jpg')
计算输入图像不同颜色(蓝色、绿色和红色)的直方图。
hist1 = cv2.calcHist([img],[0],None,[256],[0,256]) #blue hist2 = cv2.calcHist([img],[1],None,[256],[0,256]) # green hist3 = cv2.calcHist([img],[2],None,[256],[0,256]) # red
绘制输入图像不同颜色的直方图。
plt.subplot(3,1,1), plt.plot(hist1, color='b') plt.subplot(3,1,2), plt.plot(hist2, color='g') plt.subplot(3,1,3), plt.plot(hist2, color='r')
输入图像
我们将在下面的示例中使用以下图像作为输入文件。
Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.
示例 1
在本例中,我们计算三种不同颜色(蓝色、绿色和红色)的直方图,并在三个子图中绘制所有三个直方图。
# import required libraries import cv2 from matplotlib import pyplot as plt # Read the input image img = cv2.imread('birds.jpg') # calculate the histogram for Blue, green ,Red color channels hist1 = cv2.calcHist([img],[0],None,[256],[0,256]) #blue hist2 = cv2.calcHist([img],[1],None,[256],[0,256]) # green hist3 = cv2.calcHist([img],[2],None,[256],[0,256]) # red # plot the histogram plt.subplot(3,1,1), plt.plot(hist1, color='b') plt.subplot(3,1,2), plt.plot(hist2, color='g') plt.subplot(3,1,3), plt.plot(hist2, color='r') plt.show()
输出
运行此 Python 代码时,将产生以下输出:
示例 2
在本例中,我们计算三种不同颜色(蓝色、绿色和红色)的直方图,并在单个图中绘制所有三个直方图。
# import required libraries import cv2 from matplotlib import pyplot as plt # Read the input image img = cv2.imread('birds.jpg') # define the color color = ('b','g','r') # calculate and plot the histogram for i, col in enumerate(color): histr = cv2.calcHist([img],[i],None,[256],[0,256]) plt.plot(histr,color = col) plt.xlim([0,256]) plt.show()
运行此代码时,将产生以下输出窗口:
广告