gpt4 book ai didi

python - 在 matplotlib 中将一个图像动画化到另一个图像之上

转载 作者:太空宇宙 更新时间:2023-11-03 23:51:10 33 4
gpt4 key购买 nike

我一直在使用 matplotlib 为一些图像制作动画,但我现在发现我想为这些动画添加更多信息,所以我想叠加一个散点图来指示重要特征。到目前为止,这是我用来生成电影的代码:

def make_animation(frames,path,name): 

plt.rcParams['animation.ffmpeg_path'] = u'/Users/~/anaconda3/bin/ffmpeg' #ffmpeg path
n_images=frames.shape[2]
assert (n_images>1)
figsize=(10,10)
fig, ax = plt.subplots(figsize=figsize)
fig.tight_layout()
fig.subplots_adjust(left=0, bottom=0, right=1, top=1, wspace=None, hspace=None)
#lineR, = ax.plot(xaxis_data[0],R_data[0],'c-',label="resources")
img = ax.imshow(frames[:,:,0], animated = True)


def updatefig(img_num):

#lineR.set_data(xaxis_data[img_num],R_data[img_num],'r-')

img.set_data(frames[:,:,img_num])

return [img]


ani = animation.FuncAnimation(fig, updatefig, np.arange(1, n_images), interval=50, blit=True)
mywriter = animation.FFMpegWriter(fps = 20)
#ani.save('mymovie.mp4',writer=mywriter)

ani.save("/Users/~/output/"+ path + "/" + name + ".mp4",writer=mywriter)

plt.close(fig)

我想在每一帧的顶部添加一个散点图,就像我可以用这样的常规图一样:

fig, ax = plt.subplots()
img = ax.imshow(frames[:,:,0])
img = ax.scatter(scatter_pts[0],scatter_pts[1],marker='+',c='r')

我的第一次尝试是这样的:

def make_animation_scatter(frames,path,name,scatter): 

plt.rcParams['animation.ffmpeg_path'] = u'/Users/~/anaconda3/bin/ffmpeg' #ffmpeg path
n_images=frames.shape[2]
assert (n_images>1)
figsize=(10,10)
fig, ax = plt.subplots(figsize=figsize)
fig.tight_layout()
fig.subplots_adjust(left=0, bottom=0, right=1, top=1, wspace=None, hspace=None)
#lineR, = ax.plot(xaxis_data[0],R_data[0],'c-',label="resources")
img = ax.imshow(frames[:,:,0], animated = True)
img = ax.scatter(scatter[0],scatter[1],c='r',marker = '+')

def updatefig(img_num):

#lineR.set_data(xaxis_data[img_num],R_data[img_num],'r-')

img.set_data(frames[:,:,img_num])
img = ax.scatter(scatter[0],scatter[1],c='r',marker = '+')
return [img]


ani = animation.FuncAnimation(fig, updatefig, np.arange(1, n_images), interval=50, blit=True)
mywriter = animation.FFMpegWriter(fps = 20)
#ani.save('mymovie.mp4',writer=mywriter)

ani.save("/Users/~/output/"+ path + "/" + name + ".mp4",writer=mywriter)

plt.close(fig)

这会生成一个没有散点图的视频,所以我想知道如何正确地实现它。

最佳答案

docs假设当使用 blit=True 时,您必须从更新函数返回一个“可迭代的艺术家”才能重绘它们。但是,您只返回 img。此外,您正在用图像和散点对象覆盖 img。您想要的是为散点图使用不同的名称,例如

img = ax.imshow(frames[:,:,0], animated = True)
sct = ax.scatter(scatter[0],scatter[1],c='r',marker = '+')

两者仍将绘制在同一轴上,但现在您有 imgsct 艺术家,然后更新功能将是

def updatefig(img_num, img, sct, ax):
img.set_data(frames[:,:,img_num])
sct = ax.scatter(scatter[0], scatter[1], c='r', marker='+')
return [img, sct]

关于python - 在 matplotlib 中将一个图像动画化到另一个图像之上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59329794/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com