在opencv python中绘制直方图

时间:2018-01-06 10:14:16

标签: python opencv image-processing

我想通过处理前置摄像头视频来检测车辆的车道偏离。为此我想要水平选择每个帧的一个像素线并分析这些像素颜色的变化。为此,我想绘制R,G,B通道的直方图,其在x轴上从左到右具有像素数,在y轴上具有相应的像素值。由于我是这个领域的新手,我想知道如何使用opencv和python为视频中的每个帧绘制这个直方图?谢谢。

1 个答案:

答案 0 :(得分:0)

这是图像的直方图(opencv + matplotlib):

#!/usr/bin/python3
# 2017.12.20 14:00:12 CST
# 2018.01.06 19:07:57 CST
import matplotlib.pyplot as plt
import numpy as np
import cv2

img = cv2.imread("test.png")
b,g,r = cv2.split(img)
fig = plt.figure(figsize=(8,4))

ax = fig.add_subplot(121)
ax.imshow(img[...,::-1])

ax = fig.add_subplot(122)
for x, c in zip([b,g,r], ["b", "g", "r"]):
    xs = np.arange(256)
    ys = cv2.calcHist([x], [0], None, [256], [0,256])
    ax.plot(xs, ys.ravel(), color=c)

ax.set_xlabel('X')
ax.set_ylabel('Y')
plt.show()

enter image description here

以下是关于绘制3D直方图的两个示例,您可以参考。

(1) How to plot 3D histogram of an image in OpenCV

enter image description here

(2)3d plot of list of (hist, bin_edges) where histogram bar chart or lines are in the z-y plane

enter image description here