【问题标题】:Python montage a plot on OpenCV image and record as videoPython蒙太奇在OpenCV图像上绘制并录制为视频
【发布时间】:2023-03-19 12:25:02
【问题描述】:

假设您有一个采样率为 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

【问题讨论】:

  • 可能磁盘 i/o 正在减慢循环速度。我做了类似的事情,但我不会使用 matplotlib,而是使用 cv2.line、cv2.polylines 等直接在 numpy 数组图像数据(零或帧)上绘制图,然后我们可以将该 numpy 缓冲区发送到 cv2.VideoWriter 之类的你在做。
  • 你能分享从numpy数组中绘制的opencv绘图函数吗?我需要看到价值观和变化。 opencv的draw函数够用吗?
  • 如果你能得到所有点(t,nse)的x,y坐标,那么你可以使用cv2.polylines在numpy数组docs.opencv.org/2.4/modules/core/doc/…上绘制它
  • 我无法理解 x,y 坐标是什么?我只想将绘图添加到图像的侧面或下方。

标签: python-2.7 opencv matplotlib pyqtgraph


【解决方案1】:
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 应该按你喜欢的画布尺寸进行归一化。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-05
    • 2017-03-04
    • 2018-08-08
    • 1970-01-01
    • 2017-04-12
    • 2018-11-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多