python - Matplotlib 将动画保存为视频但获取空内容

标签 python matplotlib animation video visualization

我试图制作一个继续旋转图像的动画,但输出视频文件有空内容(仅留下轴),如何修复它?

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'])

最佳答案

我对您的代码进行了一些编辑:

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

请告诉我此代码是否实现了您的目标或者您是否需要任何进一步的修改。

完整代码

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)

动画

enter image description here

关于python - Matplotlib 将动画保存为视频但获取空内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72328616/

相关文章:

ios - Objective-C : how to resize uitextview height with animation?

java - 在一个程序中使用多个 Swing 定时器是不是很糟糕

java - 停止 "javax.swing.timer"不会暂停动画

python - Python 中的 HTML 解析器

python - 如何使用 pandas 有效地为序列中缺少的数据点添加行?

Python:如何制作具有逐渐变化的可变线宽的绘图?

Python:针对函数的一个变量进行绘图

python - 折叠具有重叠日期的行

python - 在QWebEngineView浏览器中保存html文件

python - 如何使用 matplotlib/pandas 绘制非堆叠且非并排的水平条形图?