【问题标题】:Error for PillowWriter in Python for exporting to .gifPython 中 PillowWriter 导出到 .gif 时出错
【发布时间】:2020-09-02 21:15:03
【问题描述】:

我正在尝试在 python 中制作一些正弦波动画,然后我可以将其导出为 .gif 格式。 我正在尝试使用 matplotlib 的 PillowWriter 函数在 Visual Studio 中执行此操作。我不断收到此“列表索引超出范围”错误,似乎无法解决。将不胜感激任何关于我做错了什么的想法。郑重声明,我对编程一窍不通,刚决定在隔离期间自学 Python 进行数据可视化,所以不幸的是,我对 Python、VS 等都很陌生。提前感谢您的任何建议。

import numpy as np
from matplotlib import pyplot as plt
from matplotlib.animation import FuncAnimation, PillowWriter
plt.style.use('seaborn-pastel')


fig = plt.figure()
ax = plt.axes(xlim=(-15, 15), ylim=(-6, 6))
line1, = ax.plot([], [], lw=3)
line2, = ax.plot([], [], lw=3)
line3, = ax.plot([], [], lw=6)
line4, = ax.plot([], [], lw=3)


def init():
    line1.set_data([], [])
    line2.set_data([], [])
    line3.set_data([], [])
    line4.set_data([], [])
    return line1, line2, line3, line4,

def animate(i):
    x = np.linspace(-15, 15, 4000)
    y = np.sin(0.21 * np.pi * (x - 0.23 * i))
    y2 = np.sin(0.311 * np.pi * (x - 0.19 * i)+2.1)
    y3 = np.sin(0.307 * np.pi * (x - 0.29 * i)+4.2)
    y4 = np.sin(0.3 * np.pi * (x - 0.4 * i))
    ##yz = np.sin(0.5(freq) * np.pi * (x - 0.4(speed) * i)(displacement))
    y5 = y+y2
    y6 = y3+y5+y5+y4
    y8 = y+y2+y3
    y7 = y8+y4

    #line1.set_data(x, 5)
    #line2.set_data(x, y6)
    line3.set_data(x, y6)
    #line4.set_data(x, y8)

    return line1, line2, line3, line4,


anim = FuncAnimation(fig, animate, init_func=init,
                               frames=2000, interval=25, blit=True)

writer = PillowWriter(fps=20) 

anim.save("sinewaves.gif", writer=writer)  

plt.show()

这是尝试保存错误所在的倒数第二行。

【问题讨论】:

    标签: python matplotlib animation python-imaging-library gif


    【解决方案1】:

    您可以这样做:

    import matplotlib.pyplot as plt
    import numpy as np
    x = np.linspace(-10,10,100)
    
    for n in range(7):
        plt.xticks([])
        plt.yticks([])
        plt.ylim(-2,2)
        plt.plot(x,np.sin(x))
        plt.savefig(str(n)+'.png')
        plt.close()
        x += 1
    
    from PIL import Image,ImageFilter
    images = []
    for n in range(7):
        exec('a'+str(n)+'=Image.open("'+str(n)+'.png")')
        images.append(eval('a'+str(n)))
    images[0].save('sin.gif',
                   save_all=True,
                   append_images=images[1:],
                   duration=100,
                   loop=0)
    

    输出:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-15
      • 2015-05-22
      相关资源
      最近更新 更多