在matplotlib中为合成图像创建动画?

时间:2019-12-18 03:36:48

标签: python matplotlib

我正在加载一组图像,并且要在每个图像上添加一个对应的“矩形补丁”。我想将它们作为连续动画播放。

frames = np.load('../data/carseq.npy') #frames
bbox = np.load('carseqrects.npy')  #bounding boxes

final_=[]
fig,ax = plt.subplots(1)
for i in range(num_frames):
    box = bbox[i]
    final_.append([plt.imshow(frames[:,:,i], cmap='Greys_r',animated=True)])
    final_.append([ax.add_patch(patches.Rectangle((box[0],box[1]),height+1,width+1, linewidth=2, 
                  edgecolor='red',fill=False))])

ani = animation.ArtistAnimation(fig, final_, interval=100, blit=True,
                                repeat_delay=1000)

plt.show()

我明白这段代码的根本错误,

final_.append([ax.add_patch(patches.Rectangle((box[0],box[1]),height+1,width+1, linewidth=2, 
                  edgecolor='red',fill=False))])

只是在上面添加了带有红色矩形的白色图,因此在清除前一帧后便绘制了该矩形-这会产生“闪烁”效果(因为矩形未完全绘制在框架本身上) 。我还有其他方法可以做到吗?

1 个答案:

答案 0 :(得分:0)

传递给ArtistAnimation的艺术家列表可以是列表列表,其中列表的每个“行”包含需要在当前帧上绘制的所有艺术家。

frames = np.load('../data/carseq.npy') #frames
bbox = np.load('carseqrects.npy')  #bounding boxes

final_=[]
fig,ax = plt.subplots(1)
for i in range(num_frames):
    cur_frame = []
    box = bbox[i]
    cur_frame.append(ax.imshow(frames[:,:,i], cmap='Greys_r',animated=True))
    cur_frame.append(ax.add_patch(patches.Rectangle((box[0],box[1]),height+1,width+1, linewidth=2, 
                  edgecolor='red',fill=False)))
    final_.append(cur_frame)

ani = animation.ArtistAnimation(fig, final_, interval=100, blit=True,
                                repeat_delay=1000)

plt.show()