所以,我想简单地采用我通过plt.plot(x,y)
制作的现有情节,将其转换为"图像",以便我可以将其提供给OpenCV'视频作者通过:
cv2.VideoWriter('myMovie.avi', fourcc, 20.0, (640,480))
writer.write(image)
我的问题是,鉴于我已经绘制的数字,我如何得到" image"?
感谢。
答案 0 :(得分:3)
在发布解决方案之前,如果您只是使用matplotlib's animation来保存视频,则可能会更容易。以下是使用opencv
:
import numpy as np
import cv2
import matplotlib.pyplot as plt
fig = plt.figure()
x1 = np.linspace(0.0, 5.0)
x2 = np.linspace(0.0, 2.0)
y1 = np.cos(2 * np.pi * x1) * np.exp(-x1)
y2 = np.cos(2 * np.pi * x2)
ax = fig.add_subplot(2,1,1)
line1, = ax.plot(x1, y1, 'ko-') # so that we can update data later
ax.set_title('A tale of 2 subplots')
ax.set_ylabel('Damped oscillation')
ay = fig.add_subplot(2, 1, 2)
ay.plot(x2, y2, 'r.-')
ay.set_xlabel('time (s)')
ay.set_ylabel('Undamped')
for i in range(1000):
# update data
line1.set_ydata(np.cos(2 * np.pi * (x1+i*3.14/2) ) * np.exp(-x1) )
# redraw the canvas
fig.canvas.draw()
# convert canvas to image
img = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep='')
img = img.reshape(fig.canvas.get_width_height()[::-1] + (3,))
# img is rgb, convert to opencv's default bgr
img = cv2.cvtColor(img,cv2.COLOR_RGB2BGR)
# display image with opencv or any operation you like
cv2.imshow("plot",img)
k = cv2.waitKey(33) & 0xFF
if k == 27:
break
答案 1 :(得分:0)
由于我没有足够的声誉来评论Quang Houang的出色答案。我写一些东西作为答案。它警告不推荐使用np.fromstring。您可以像这样使用np.frombuffer。
img = np.frombuffer(fig.canvas.tostring_rgb(), dtype=np.uint8)