Matplotlib 将动画保存为视频但内容为空

Matplotlib save animaiton as video but get empty content

我正在尝试制作一个继续旋转图像的动画,但输出的视频文件内容为空(只剩下轴),如何解决?

import math

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import scipy.misc
from scipy import ndimage

my_image="img.png"
out_file="myvideo.mp4"

class UpdateDist:
    def __init__(self, ax):
        self.ax = ax
        self.img = mpimg.imread(my_image)
        self.ax.imshow(self.img)
        self.degree = 1


    def __call__(self, i):
        rotated_img = ndimage.rotate(img, self.degree*10)
        self.ax.imshow(rotated_img)
        self.degree += 1
        return self.ax,


plt.axis(False)
plt.grid(False)
fig, ax = plt.subplots()


ud = UpdateDist(ax)
anim = FuncAnimation(fig, ud, frames=100, interval=10, blit=True)
plt.show()
ani.save(out_file, fps=30, extra_args=['-vcodec', 'libx264'])

我对您的代码进行了一些修改:

  • i替换了self.degreei在每次迭代中增加1,不需要另一个计数器
  • __call__ 方法中移动了 ax.grid(False)ax.axis(False)(并添加了 ax.clear()),以便在每个帧中使用它们
  • FuncAnimation
  • 中删除了 blit 参数
  • .mp4 输出文件格式替换为 .gif
  • 已将 imagemagik 用作 writer

让我知道此代码是否实现了您的目标,或者您是否需要进一步修改。

完整代码

import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
from scipy import ndimage
import numpy as np


my_image='img.png'
out_file='myvideo.gif'


class UpdateDist:

    def __init__(self, ax, rotational_speed):
        self.ax = ax
        self.img = plt.imread(my_image)
        self.rotational_speed = rotational_speed

    def __call__(self, i):
        rotated_img = ndimage.rotate(self.img, self.rotational_speed*i, reshape=False)
        self.ax.clear()
        self.ax.grid(False)
        self.ax.axis(False)
        self.ax.imshow((rotated_img*255).astype(np.uint8))
        return self.ax,


fig, ax = plt.subplots()

ud = UpdateDist(ax = ax, rotational_speed = 1)
anim = FuncAnimation(fig, ud, frames = 91, interval = 1)
anim.save(filename = out_file, writer = 'pillow', fps = 30)

动画