在matplotlib中将一张图片叠加到另一张图片上并实现动画效果

3

我一直在使用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)

这将生成一个没有散点图的视频,因此我想知道如何正确实现它。

“它不起作用”确切地是什么意思? - ImportanceOfBeingErnest
它只生成帧而不是散点图的视频。我已经编辑了问题以使其更清晰,谢谢提问。 - algol
1
以下答案是否解决了这个问题?(如果是,请接受它) - ImportanceOfBeingErnest
是的,我之前没有时间测试它。 - algol
1个回答

5

文档中提到,当使用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]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接