我正在尝试使用OpenCV实时绘制来自摄像机的一些数据。但是,实时绘图(使用matplotlib)似乎不能正常工作。
我把这个问题隔离在这个简单的例子中:
fig = plt.figure()
plt.axis([0, 1000, 0, 1])
i = 0
x = list()
y = list()
while i < 1000:
temp_y = np.random.random()
x.append(i)
y.append(temp_y)
plt.scatter(i, temp_y)
i += 1
plt.show()
我希望这个例子能分别画出1000个点。实际发生的情况是,窗口弹出,显示第一个点(好吧),然后等待循环结束,然后填充图的其余部分。
有什么想法,为什么我没有看到点填充一个时间?
这是使用while循环绘制动态实时matplot动画的正确方法
有一篇关于这方面的文章:
PIP安装赛璐珞#这将捕获图像/动画
import matplotlib.pyplot as plt
import numpy as np
from celluloid import Camera # getting the camera
import matplotlib.animation as animation
from IPython import display
import time
from IPython.display import HTML
import warnings
%matplotlib notebook
warnings.filterwarnings('ignore')
warnings.simplefilter('ignore')
fig = plt.figure() #Empty fig object
ax = fig.add_subplot() #Empty axis object
camera = Camera(fig) # Camera object to capture the snap
def f(x):
''' function to create a sine wave'''
return np.sin(x) + np.random.normal(scale=0.1, size=len(x))
l = []
while True:
value = np.random.randint(9) #random number generator
l.append(value) # appneds each time number is generated
X = np.linspace(10, len(l)) # creates a line space for x axis, Equal to the length of l
for i in range(10): #plots 10 such lines
plt.plot(X, f(X))
fig.show() #shows the figure object
fig.canvas.draw()
camera.snap() # camera object to capture teh animation
time.sleep(1)
以及用于储蓄等:
animation = camera.animate(interval = 200, repeat = True, repeat_delay = 500)
HTML(animation.to_html5_video())
animation.save('abc.mp4') # to save
输出是:
另一种选择是使用散景。在我看来,至少对于实时情节来说,这是一个不错的选择。下面是问题中代码的散景版本:
from bokeh.plotting import curdoc, figure
import random
import time
def update():
global i
temp_y = random.random()
r.data_source.stream({'x': [i], 'y': [temp_y]})
i += 1
i = 0
p = figure()
r = p.circle([], [])
curdoc().add_root(p)
curdoc().add_periodic_callback(update, 100)
对于运行它:
pip3 install bokeh
bokeh serve --show test.py
Bokeh通过websocket通信在web浏览器中显示结果。当数据由远程无头服务器进程生成时,它尤其有用。
下面是问题代码的工作版本(至少需要2011年11月14日的Matplotlib 1.1.0版本):
import numpy as np
import matplotlib.pyplot as plt
plt.axis([0, 10, 0, 1])
for i in range(10):
y = np.random.random()
plt.scatter(i, y)
plt.pause(0.05)
plt.show()
请注意对plt.pause(0.05)的调用,它既绘制新数据,又运行GUI的事件循环(允许鼠标交互)。