Ошибка экспорта анимации в gif - Matplotlib - PullRequest
1 голос
/ 31 марта 2020

Я хочу экспортировать анимацию в формате GIF. Я могу добиться этого с помощью mp4, но получаю ошибку при преобразовании в GIF. Я не уверен, что это неверный скрипт или какие-то настройки бэкенда.

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import animation

df1 = pd.DataFrame({
    'Time' : [1,1,1,2,2,2,3,3,3],        
    'GroupA_X' : [3, 4, 5, 12, 15, 16, 21, 36, 47], 
    'GroupA_Y' : [2, 4, 5, 12, 15, 15, 22, 36, 45],            
    'GroupB_X' : [2, 5, 3, 12, 14, 12, 22, 33, 41],   
    'GroupB_Y' : [2, 4, 3, 13, 13, 14, 24, 32, 45],                 
        })

fig, ax = plt.subplots()
ax.grid(False)
ax.set_xlim(0,50)
ax.set_ylim(0,50)

def groups():

    Group_A = df1[['Time','GroupA_X','GroupA_Y']]

    GA_X = np.array(Group_A.groupby(['Time'])['GroupA_X'].apply(list))
    GA_Y = np.array(Group_A.groupby(['Time'])['GroupA_Y'].apply(list))

    GA = ax.scatter(GA_X[0], GA_Y[0], c = ['blue'], marker = 'o', s = 10, edgecolor = 'black')

    return GA, GA_X, GA_Y

def animate(i) :

    GA, GA_X, GA_Y = groups()

    GA.set_offsets(np.c_[GA_X[0+i], GA_Y[0+i]])


ani = animation.FuncAnimation(fig, animate, np.arange(0,3), interval = 1000, blit = False)

# If exporting as an mp4 it works fine.

#Writer = animation.writers['ffmpeg']
#writer = Writer(fps = 10, bitrate = 8000)
#ani.save('ani_test.mp4', writer = writer)


#But if I try to export as a gif it returns an error:

ani.save('gif_test.gif', writer = 'imagemagick')

Ошибка:

MovieWriter imagemagick unavailable. Trying to use pillow instead.

self._frames[0].save(
IndexError: list index out of range

Примечание: я также пробовал следующее, которое возвращает тот же Index error

my_writer=animation.PillowWriter(fps = 10)
ani.save(filename='gif_test.gif', writer=my_writer)

Я пытался настроить многочисленные параметры из других вопросов animate gif . Мои текущие настройки анимации следующие. Я использую Ма c.

###ANIMATION settings
#animation.html :  none            ## How to display the animation as HTML in
                                   ## the IPython notebook. 'html5' uses
                                   ## HTML5 video tag; 'jshtml' creates a 
                                   ## Javascript animation
#animation.writer : imagemagick         ## MovieWriter 'backend' to use
#animation.codec : mpeg4            ## Codec to use for writing movie
#animation.bitrate: -1             ## Controls size/quality tradeoff for movie.
                                   ## -1 implies let utility auto-determine
#animation.frame_format:  png      ## Controls frame format used by temp files
#animation.html_args:              ## Additional arguments to pass to html writer
animation.ffmpeg_path: C:\Program Files\ImageMagick-6.9.1-Q16\ffmpeg.exe    ## Path to ffmpeg binary. Without full path
                                   ## $PATH is searched
#animation.ffmpeg_args:            ## Additional arguments to pass to ffmpeg
#animation.avconv_path:  avconv    ## Path to avconv binary. Without full path
                                   ## $PATH is searched
#animation.avconv_args:            ## Additional arguments to pass to avconv
animation.convert_path: C:\Program Files\ImageMagick-6.9.2-Q16-HDRI    ## Path to ImageMagick's convert binary.
                                   ## On Windows use the full path since convert
                                   ## is also the name of a system tool.
#animation.convert_args:           ## Additional arguments to pass to convert
#animation.embed_limit : 20.0

Ответы [ 2 ]

1 голос
/ 03 апреля 2020

Пути, которые вы настроили,

animation.ffmpeg_path: C:\Program Files\ImageMagick-6.9.1-Q16\ffmpeg.exe

и

animation.convert_path: C:\Program Files\ImageMagick-6.9.2-Q16-HDRI

Для Windows, но, поскольку вы находитесь на Ma c, вам нужны пути для MacOS. Вы должны быть в состоянии получить их, используя which из терминала. На моем Ubuntu установка which дает следующее

>$ which convert
/usr/bin/convert

>$ which ffmpeg  
/usr/bin/ffmpeg

Это должно быть похоже на MacOS. Это пути, которые необходимо указать для rcParams animation.convert_path и animation.ffmpeg_path, то есть

animation.ffmpeg_path: /usr/bin/ffmpeg
animation.convert_path: /usr/bin/convert

Обратите внимание, что неправильные пути в конфигурации matplotlib приведут к указанной ошибке, исправляя это может не устранить ошибку - возможно, что-то не так.

1 голос
/ 31 марта 2020

Я нашел решение из поста аналогичного вопроса . Кажется, что класс PillowWriter работал на моем компьютере, я не мог преодолеть ошибку, возникающую из класса ImageMagick. Вы можете иметь лучшее представление о том, как установить битрейт и код c, это были предположения или скопированы из вопроса, который я упоминал ранее.

ani = animation.FuncAnimation(fig, new_animate, frames=np.arange(0, 3)
plt.show()

my_writer=animation.PillowWriter(fps=20, codec='libx264', bitrate=2)

ani.save(filename='gif_test.gif', writer=my_writer)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...