2014-04-19 7 views
4

유한 요소법을 사용하여 2D 열 흐름 문제에 대해 생성 한 일련의 표면 플롯에 애니메이션을 적용하려고했습니다. 매 시간 단계마다 더 효율적으로 전체 행렬 대신 음모를 저장했습니다.ArtistAnimation을 사용하여 matplotlib에서 png 애니메이션하기

matplotlib.animation 라이브러리의 FuncAnimation에 문제가있어서 매번 표면 플롯을 렌더링하고 표면 플롯을 .png 파일로 저장 한 다음 pyplot.imread을 사용하여 해당 이미지를 읽습니다. 거기에서 각 이미지를 목록에 저장하여 ArtistAnimation (example)을 사용할 수있게하려고합니다. 그러나 애니메이션을 만들지 않고 화면에 imgplot을 인쇄 할 때 두 개의 빈 공백 플롯과 내 표면 플롯 .png가 생깁니다.

또한, 내가 애니메이션을 저장하려고하면, 나는 다음과 같은 오류 메시지가 :

AttributeError: 'module' object has no attribute 'save'. 

목록에서 그들을 저장 현재 디렉토리에서 .pngs 세트에서 독서에 어떤 도움, 및 그런 다음 ArtistAnimation을 사용하여 해당 .png을 "애니메이트"하면 큰 도움이됩니다. 나는 아무것도 좋아할 필요가 없다.

(주 - 나는 코드가 자동화하기 위해, 그래서 불행하게도 나는 iMovie에서 나는 FFmpeg처럼 내 이미지를 애니메이션으로 외부 소스를 사용할 수 없습니다.) 아래

내 코드입니다 :

from numpy import * 
from pylab import * 
import matplotlib.pyplot as plt 
import matplotlib.image as mgimg 
from matplotlib import animation 

## Read in graphs 

p = 0 
myimages = [] 

for k in range(1, len(params.t)): 

    fname = "heatflow%03d.png" %p 
     # read in pictures 
    img = mgimg.imread(fname) 
    imgplot = plt.imshow(img) 

    myimages.append([imgplot]) 

    p += 1 


## Make animation 

fig = plt.figure() 
animation.ArtistAnimation(fig, myimages, interval=20, blit=True, repeat_delay=1000) 

animation.save("animation.mp4", fps = 30) 
plt.show() 

답변

2

문제 1 : 이미지가 표시되지 당신은 변수에 애니메이션 객체를 저장할 필요가

:

my_anim = animation.ArtistAnimation(fig, myimages, interval=100) 

이 요구 사항은 animation에만 해당하며 matplotlib의 다른 플로팅 기능과 일치하지 않습니다. 일반적으로 my_plot=plt.plot() 또는 plt.plot()을 무관계하게 사용할 수 있습니다.

이 질문에 대한 자세한 내용은 here입니다.

문제 2 : 저장 어떤 animation 예를없이

작동하지 않습니다, 하나 그림을 저장 할 수 없습니다. 이는 save 방법 이 ArtistAnimation 클래스에 속하기 때문입니다. 귀하가 수행 한 작업은 animation 모듈에서 save으로 전화를 걸었습니다. 이것이 오류의 원인입니다.

문제 3 : 두 개의 창

마지막 문제는이 두 인물이 진열 얻을 수 있다는 것입니다. 그 이유는 plt.imshow()으로 전화를 걸면 현재 그림에 이미지가 표시되지만 그림이 아직 생성되지 않았기 때문에 pyplot이 암시 적으로 만들어집니다. 파이썬이 나중에 fig = plt.figure() 문을 해석하면 새로운 그림 (다른 창)이 만들어지고 "그림 2"라는 레이블이 붙습니다. 이 문을 코드 시작 부분으로 이동하면 해당 문제가 해결됩니다.

import matplotlib.pyplot as plt 
import matplotlib.image as mgimg 
from matplotlib import animation 

fig = plt.figure() 

# initiate an empty list of "plotted" images 
myimages = [] 

#loops through available png:s 
for p in range(1, 4): 

    ## Read in picture 
    fname = "heatflow%03d.png" %p 
    img = mgimg.imread(fname) 
    imgplot = plt.imshow(img) 

    # append AxesImage object to the list 
    myimages.append([imgplot]) 

## create an instance of animation 
my_anim = animation.ArtistAnimation(fig, myimages, interval=1000, blit=True, repeat_delay=1000) 

## NB: The 'save' method here belongs to the object you created above 
#my_anim.save("animation.mp4") 

## Showtime! 
plt.show() 

(. 그냥 "heatflow003.png"을 통해 이름 "heatflow001.png"당신의 작업 폴더에 3 개 이미지를 추가, 위의 코드를 실행하려면)

: 여기

수정 된 코드입니다 먼저 목록에서 이미지를 수집하기 때문에, FuncAnimation을 사용하려고 할 때 당신은 아마 옳았다 FuncAnimation

메모리의 측면에서 비용이 많이 드는 사용

다른 방법. 아래의 코드를 위의 코드와 비교하여 시스템 모니터의 메모리 사용량을 비교하여 테스트했습니다. FuncAnimation 접근 방식이 더 효과적 인 것으로 보입니다. 나는 당신이 더 많은 이미지를 사용함에 따라 차이가 더 커질 것이라고 믿습니다.

from matplotlib import pyplot as plt 
from matplotlib import animation 
import matplotlib.image as mgimg 
import numpy as np 

#set up the figure 
fig = plt.figure() 
ax = plt.gca() 

#initialization of animation, plot array of zeros 
def init(): 
    imobj.set_data(np.zeros((100, 100))) 

    return imobj, 

def animate(i): 
    ## Read in picture 
    fname = "heatflow%03d.png" % i 

    ## here I use [-1::-1], to invert the array 
    # IOtherwise it plots up-side down 
    img = mgimg.imread(fname)[-1::-1] 
    imobj.set_data(img) 

    return imobj, 


## create an AxesImage object 
imobj = ax.imshow(np.zeros((100, 100)), origin='lower', alpha=1.0, zorder=1, aspect=1) 


anim = animation.FuncAnimation(fig, animate, init_func=init, repeat = True, 
           frames=range(1,4), interval=200, blit=True, repeat_delay=1000) 

plt.show() 
: 여기

번째 코드
관련 문제