python - 如何从 opencv while 循环运行动画图?
问题描述
我已经为此工作了数周,我确信这是由于我缺乏基本的 Python 知识。我需要使用 MatplotlibFuncAnimation
函数制作动画。到目前为止,我能够通过使用 while 循环将我的 y 值生成到一个列表中(这些值上下波动,当用 x 轴上的框架绘制时,它应该创建一个看起来类似于心脏监视器的图形)。
我似乎总是遇到两个主要问题:
1) 我永远无法访问从 while 循环创建的数据并将其用于我的图表。
FuncAnimation
2)在同时运行 opencv while 循环时,我永远无法使用该函数绘制图形。
有人可以花点时间查看我当前的代码并指出主要缺陷,我相信它看起来会很混乱,但我不知道从哪里开始让这个东西工作。我要从头开始。
import numpy as np
import cv2
import matplotlib.pyplot as plt
import matplotlib.animation as animation
# Parameters
x_len = 200 # Number of points to display
y_range = [10, 40] # Range of possible Y values to display
# Create figure for plotting
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
xs = list(range(0, 200))
ys = [0] * x_len
ax.set_ylim(y_range)
# Create a blank line. We will update the line in animate
line, = ax.plot(xs, ys)
def animate(i, ys):
ys.append(avg)
ys = ys[-x_len:]
line.set_ydata(ys)
return line,
def data_gen():
average = (np.average(difference))
average_int = int(average)
return average_int
def initialize_camera(cap):
_, frame = cap.read()
return frame
#Set up plot to call animate() function periodically
ani = animation.FuncAnimation(fig, animate, fargs=(ys,), interval=50, blit=True)
plt.show()
if __name__ == '__main__':
cap = cv2.VideoCapture(0)
first_frame = initialize_camera(cap)
while cap.isOpened():
ret, frame = cap.read( )
difference = cv2.absdiff(first_frame, frame)
_, difference = cv2.threshold(difference, 18, 255, cv2.THRESH_BINARY)
avg = data_gen()
cv2.imshow('first frame', first_frame)
cv2.imshow('Original', frame)
cv2.imshow('difference', difference)
print(avg)
key = cv2.waitKey(30) & 0xff
if key == 27:
break
cap.release()
cv2.destroyAllWindows()
print('End Stream')
创建所有数据的 while 循环在 if 语句中if __name__ == '__main__':
,这需要运行并创建我的 y 值。然后我想用 200 点的静态 x 轴绘制它。我需要使用该FuncAnimation
功能和 blitting 以获得足够的 FPS 来准确读取数据。
解决方案
推荐阅读
- javascript - 反应角色使用 discord.js 和 mysql
- java - 如何获取输入来执行列表元素的总和?
- mysql - nodejs中的foreach循环
- excel - 如何将文件内容从 xlsm 复制到另一个 xlsm?
- javascript - 如何在 JavaScript 中通过单击事件侦听器方法将新引号示例添加到对象现有数组中
- azure - 无法从 Azure 虚拟机访问 Blob
- python - 如何在 tensorflow 1.x 中标准化张量信号
- signals - CRC算法的效率如何?
- sql - Laravel 和嵌套关系列
- flutter - 元素类型“字符串”不能分配给列表类型“小部件”