Python 在 OpenCV 图像上蒙太奇绘图并录制为视频

Python montage a plot on OpenCV image and record as video

假设你有一个采样率为512的温度数据。我想通过与相机图像同步来记录这个数据。生成的记录将只是一个视频文件。

我可以用 matplotlib 和 pyqtgraph 绘制这些数据。

我用 matplotlib 做到了,但视频采样率正在下降。这是带有随机传入数据的代码。

import cv2
import numpy as np
import matplotlib.pyplot as plt

cap = cv2.VideoCapture(0) # video source: webcam
fourcc = cv2.cv.CV_FOURCC(*'XVID') # record format xvid
out = cv2.VideoWriter('output.avi',fourcc, 1, (800,597)) # output video : output.avi
t = np.arange(0, 512, 1)# sample time axis from 1 to 512

while(cap.isOpened()): # record loop
    ret, frame = cap.read()# get frame from webcam
    if ret==True:
        nse = np.random.randn(len(t))# generate random data squence
        plt.subplot(1, 2, 1)# subplot random data
        plt.plot(t, nse)
        plt.subplot(1, 2, 2)# subplot image
        plt.imshow(frame)
        # save matplotlib subplot as last.png
        plt.savefig("last.png")
        plt.clf()
        img=cv2.imread("last.png") # read last.png
        out.write(img) # record last.png image to output.avi 
        cv2.imshow('frame',img)

        if cv2.waitKey(1) & 0xFF == ord('q'): # exit with press q button in frame window
            break
    else:
        break
cap.release() # relase webcam
out.release() # save video
cv2.destroyAllWindows() # close all windows
import cv2

canvas = np.zeros((480,640))

t = np.arange(0, 512, 1) # sample time axis from 1 to 512
nse = np.random.randn(len(t)) 

# some normalization to fit to canvas dimension
t = 640 * t / 512 
nse = 480 * nse / nse.max()

pts = np.vstack((t,nse)).T.astype(np.int)

cv2.polylines(canvas, [pts], False, 255)

imshow(canvas, 'gray')

这会在新的零数组 (480 x 640) 中创建绘图。 t 和 nse 应该按你喜欢的 canvas 维度归一化。

如果您的捕获帧也有 480,640 维,那么您可以为 960x640 准备 cv2.VideoWriter 并使用 np.concatenate 或 np.hstack 连接帧和 canvas 以获得 960x640 数组可以用作发送到VideoWriter的缓冲区。