Use opencv-python and matplotlib to realize the dynamic display of video color histogram

Introduction

For a picture, its color histogram can be calculated, and for a video, the color histogram of each frame can be calculated frame by frame. Recently, I need to extract the histogram of the video, but the ffmpeg command can only print the histogram on the video, and cannot export the data of the histogram, so I can only find another way to manually write one.

environment

vscode (anaconda's python path is configured).
opencv-python library
matplotlib library

the code

import cv2
import matplotlib.pyplot as plt
plt.ion() #开启动态绘图
plt.figure() #建立图窗
cap = cv2.VideoCapture('I(720p).avi')  #调用本地文件,如果为0则调成实时摄像头
while(True):
    plt.clf() #清屏,如果不清则会无限叠加之前的作图
    ret, frame = cap.read() #ret为True or False,frame为读取的每帧图像的数组
    if ret == False:
        break; #帧读取完的时候ret就会从True变成False
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) #进行灰度处理
    cv2.imshow('Grayscale', gray) #展示视频图像
    hist = cv2.calcHist([gray],[0],None,[256],[0,256]) #计算直方图
    plt.plot(hist)  #作图
    plt.draw()      #绘图展现
    cv2.waitKey(1)  #等待1ms 可替换成plt.pause()
cap.release()

The minimalist code of 19 lines can be expanded by itself. Generally speaking, it reads the image frame by frame, and then uses the cv2.calcHist function to calculate the histogram. The number of bins is 256, corresponding to 0-255 pixel values. The returned is the hist array, which needs to be drawn using plt.plot. At the same time, you can also write code here to export it for subsequent processing.
The biggest problem I encountered was the dynamic display. Please test the environment by yourself. I ran the py file directly and said that there is no problem. If it is a jupyter notebook environment, you may need the figure.canvas.draw() function, which has no effect here.

achieve effect

insert image description here
Image too large and cropped. You need to adjust the window size by yourself.

Guess you like

Origin blog.csdn.net/weixin_43945848/article/details/123706099