import cv2, time
import numpy as np
import matplotlib.pyplot as plt
def read_video(video_path=None, fps=60):
print("Press 'esc' for exit...")
if video_path is None:
video_path = "Real-time"
video = cv2.VideoCapture(0)
else:
video = cv2.VideoCapture(video_path)
plt.ion()
cv2.namedWindow(video_path, 0)
last_hists = []
gray_hist_dists, r_hist_dists, g_hist_dists, b_hist_dists = [], [], [], []
while 1:
ret, frame = video.read()
if cv2.waitKey(int(1000 / fps)) == 27 or not ret: # "ESC":27,“esc”退出
break
cv2.imshow(video_path, frame)
""" hist map : cv2 show"""
frame_gray = cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY)
gray_hist = cv2.calcHist([frame_gray],[0],None,[256],[0,256])
r_hist = cv2.calcHist([frame],[0],None,[256],[0,256])
g_hist = cv2.calcHist([frame],[1],None,[256],[0,256])
b_hist = cv2.calcHist([frame],[2],None,[256],[0,256])
plt.clf()
plt.plot(gray_hist, color='gray', label="gray")
plt.plot(r_hist, color='r', label="r channel")
plt.plot(g_hist, color='g', label="g channel")
plt.plot(b_hist, color='b', label="b channel")
plt.grid()
plt.legend()
fig = plt.gcf()
fig.canvas.draw() # 将figure渲染到canvas中
image = np.array(fig.canvas.renderer.buffer_rgba()) # 从canvas中获取图像数据
cv2.imshow("hist map", image)
""" hist map dist: plt show """
last_hists.append([gray_hist, r_hist, g_hist, b_hist])
if len(last_hists) == 2:
gray_hist_dists.append(cv2.compareHist(last_hists[0][0], last_hists[1][0], cv2.HISTCMP_CHISQR)) # cv2.HISTCMP_CORREL
r_hist_dists.append(cv2.compareHist(last_hists[0][1], last_hists[1][1], cv2.HISTCMP_CHISQR))
g_hist_dists.append(cv2.compareHist(last_hists[0][2], last_hists[1][2], cv2.HISTCMP_CHISQR))
b_hist_dists.append(cv2.compareHist(last_hists[0][3], last_hists[1][3], cv2.HISTCMP_CHISQR))
plt.clf()
plt.plot(gray_hist_dists, color='gray', label="gray dist")
plt.plot(r_hist_dists, color='pink', label="r channel dist")
plt.plot(g_hist_dists, color='yellow', label="g channel dist")
plt.plot(b_hist_dists, color='black', label="b channel dist")
plt.grid()
plt.legend()
last_hists.pop(0)
video.release()
cv2.destroyAllWindows()
plt.ioff()
plt.close()
if __name__ == "__main__":
# open video file
video_path = "01.mp4"
read_video(video_path)
# # open real-time video
# read_video()
由于用plt同时动态绘制两张图较为困难,将其中一张从plt图像转化为numpy格式再由 cv2 显示。