如何从opencv while循环运行动画图?

时间:2019-05-02 20:29:06

标签: python opencv matplotlib

我已经为此工作了几周了,我敢肯定这是由于我缺乏基本的python知识。我需要使用Matplotlib FuncAnimation函数制作动画。到目前为止,我可以使用while循环将y值生成到列表中(这些值上下波动,当在x轴上绘制框架时,这将创建类似于心脏监护仪的图形)。

我似乎总是遇到两个主要问题:

1)我永远无法访问从while循环创建的数据并将其用于图形。

2)在运行opencv while循环的同时,我永远无法使用FuncAnimation函数来绘制图形。

有人可以花点时间查看我当前的代码并指出主要缺陷,我敢肯定它看起来会很混乱,但是我不知道从哪里开始可以使这个东西正常工作。我将从头开始。

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函数并进行提示操作,以具有足够的FPS来准确读取数据。

0 个答案:

没有答案