动态绘制视频流直方图及直方图距离曲线

在这里插入图片描述

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 显示。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值