在OpenCV里实现彩色图像的直方图显示

由于彩色图像是由三个颜色组成,因此需要先把彩色图像进行分离成三个颜色平面,才可以按每种颜色去计算直方图,这样就是通过calcHist函数来统计数据出来,再通过matplotlib来显示出来,演示代码如下:

#python 3.7.4,opencv4.1
#蔡军生 https://blog.csdn.net/caimouse/article/details/51749579
#[email protected]
#
import numpy as np
import cv2
from matplotlib import pyplot as plt

#读取图片
img = cv2.imread('szsj.jpg')
img1 = cv2.resize(img, (400, 300))
cv2.imshow("Original", img1)

#
chans = cv2.split(img)
colors = ("b", "g", "r")

plt.figure()
plt.title("’Flattened’ Color Histogram")
plt.xlabel("Bins")
plt.ylabel("# of Pixels")

for (chan, color) in zip(chans, colors):
    hist = cv2.calcHist([chan], [0], None, [256], [0, 256])
    plt.plot(hist, color = color)
    plt.xlim([0, 256])

plt.show()
#
cv2.waitKey(0)
cv2.destroyAllWindows()
 

结果输出如下:

猜你喜欢

转载自blog.csdn.net/caimouse/article/details/103256471