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

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.degree替换为i:i在每次迭代中增加1,不需要另一个计数器
  • __call__方法中移动ax.grid(False)ax.axis(False)(并添加ax.clear()),以便在每个帧中使用它们
  • Func动画中删除了blit参数
  • .mp4输出文件格式替换为.gif
  • 使用imagemagik作为writer

让我知道这个代码是否达到了您的目标,或者您是否需要进一步的修改.

完整代码

import matplotlib.pyplot as plt
from matplotlib.animation import Func动画
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 = Func动画(fig, ud, frames = 91, interval = 1)
anim.save(filename = out_file, writer = 'pillow', fps = 30)

动画

enter image description here

Python相关问答推荐

Python多处理:当我在一个巨大的pandas数据框架上启动许多进程时,程序就会陷入困境

_repr_html_实现自定义__getattr_时未显示

优化pytorch函数以消除for循环

如何从pandas的rame类继承并使用filepath实例化

ThreadPoolExecutor和单个线程的超时

driver. find_element无法通过class_name找到元素'""

什么是最好的方法来切割一个相框到一个面具的第一个实例?

用砂箱开发Web统计分析

Django—cte给出:QuerySet对象没有属性with_cte''''

考虑到同一天和前2天的前2个数值,如何估算电力时间序列数据中的缺失值?

启动带有参数的Python NTFS会导致文件路径混乱

在pandas/python中计数嵌套类别

基于Scipy插值法的三次样条系数

Gunicorn无法启动Flask应用,因为无法将应用解析为属性名或函数调用.'"'' "

巨 Python :逆向猜谜游戏

使用tqdm的进度条

Pythonquests.get(Url)返回Colab中的空内容

FileNotFoundError:[WinError 2]系统找不到指定的文件:在os.listdir中查找扩展名

Groupby并在组内比较单独行上的两个时间戳

将时间序列附加到数据帧