试图在matplotlib动画上绘制静止的半可视图像

2024-04-24 18:41:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个用Jupyter笔记本中编写的代码制作的动画:

fig,ax=plt.subplots()
ax.set_xlim((0,512))
ax.set_ylim((0,512))

im=ax.imshow(data[0,:,:]) 
def init ():
    im.set_data(data[0,:,:])
    return(im,)
def animate(i):
    data_slice=data[i,:,:]
    im.set_data(data_slice)
    return(im,)


ani.FuncAnimation(fig,animate,init_func=init,frames=240,interval=100)

我不知道如何在它上面绘制第一帧,同时使它半透明并保持动画在背景中播放。我怎样才能做到这一点

提前谢谢


Tags: 代码datareturninitdeffig笔记本jupyter
1条回答
网友
1楼 · 发布于 2024-04-24 18:41:31

您必须创建两个图像,一个位于顶部,另一个由animate()修改:

# create dummy data
data = np.random.random(size=(240,512,512))
# load an image in first frame of data
temp = plt.imread('./stinkbug.png')
data[0,:,:] = 0.5
data[0,:375,:500] = temp[::-1,::-1,0]


fig,ax=plt.subplots()
ax.set_xlim((0,512))
ax.set_ylim((0,512))

top_img = ax.imshow(data[0,:,:], zorder=10, alpha=0.5, cmap='gray')
bottom_img = ax.imshow(data[1,:,:], zorder=1, cmap='viridis')

def init():
    top_img.set_data(data[0,:,:])
    bottom_img.set_data(data[1,:,:])
    return (top_img, bottom_img)
def animate(i):
    data_slice=data[i,:,:]
    bottom_img.set_data(data_slice)
    return (bottom_img,)


ani = animation.FuncAnimation(fig,animate,init_func=init,frames=range(1,240),interval=100)
plt.show()

enter image description here

相关问题 更多 >