2014-10-29 69 views
1

我創建了一個matplotlib動畫,它通過文件中的一系列圖像運行。我可視化的文件通常非常大,並且每個圖像堆棧都有相當長的加載時間(約5秒)。我設法通過使用多處理功能錯開加載過程來讓動畫順利運行,但我無法將動畫另存爲視頻文件。python matplotlib animation使用多重處理時保存錯誤

下面的代碼:

from matplotlib import animation 
import pylab as plt 
import numpy as np 
import multiprocessing as mp 
import logging 
logger = mp.log_to_stderr(logging.INFO) 
import time 

def qloader(queue, threshold=100, nfiles=3): 
    '''trigger a load process if number of items in queue drops below threshold''' 
    while nfiles: 
     if queue.qsize() < threshold: 
      logger.info('qsize {}'.format(queue.qsize())) 

      time.sleep(1)  #pretend to load data 
      data = np.random.rand(25,100,100) 

      logger.info('Adding data to queue') 
      for d in data: 
       queue.put(d) 
      logger.info('Done adding data!') 
      nfiles -= 1 
    else: 
     queue.put(None)  #sentinal 

def update(frame, im, queue): 
    '''update the image''' 
    logger.info('Updating frame %d'%frame) 
    data = queue.get() 
    if data is None: 
     print('Queue is empty!') 
     return 

    im.set_data(data) 
    return im 


#create data queue 
mgr = mp.Manager() 
queue = mgr.Queue() 
threshold = 20   # 

#start load process 
p = mp.Process(name='loader', target=qloader, args=(queue, threshold)) 
p.start() 

#start animation 
fig, ax = plt.subplots() 
im = ax.imshow(np.random.rand(100,100)) 
ani = animation.FuncAnimation(fig, update, frames=75, interval=100, repeat=0, fargs=(im, queue)) 
ani.save('foo.mp4', 'ffmpeg') 

代碼運行沒有錯誤,但它產生的文件被莫名其妙地損壞。當我試着使用VLC查看我弄了半天重複錯誤流...

$ vlc foo.mp4 
VLC media player 2.0.8 Twoflower (revision 2.0.8a-0-g68cf50b) 
[0xf69108] main libvlc: Running vlc with the default interface. Use 'cvlc' to use vlc without interface. 
[0x7f37fcc01ac8] mp4 demux error: cannot find any /moov/trak 
[0x7f37fcc01ac8] es demux error: cannot peek 
... 
[0x7f37fcc01ac8] ps demux error: cannot peek 
[0x7f37fcc01ac8] mpgv demux error: cannot peek 
[0x7f37fcc01ac8] mjpeg demux error: cannot peek 
[0x7f37fcc01ac8] ps demux error: cannot peek 
[0x7f3824000b78] main input error: no suitable demux module for `file/://.../foo.mp4' 
... 

我試圖保存各種文件格式,使用不同的作家和編碼器,具有許多相同的結果。

只有在使用multiprocessing加載數據時纔會出現此問題。如果我只是使用data = np.random.rand(75,100,100)創建數據,則動畫保存沒有問題。

問題:我該如何獲得matplotlib.animationmultiprocessing一起玩?

+0

即使隊列爲空,也請嘗試返回「im」。 – tacaswell 2014-10-29 14:13:08

+0

試過。失敗。據我所知,'vlc' demux錯誤表示缺少數據。輸出文件的大小隻有幾個字節,所以我認爲沒有任何幀正在寫入光盤。 – astroMonkey 2014-10-30 09:35:22

+0

正在嘗試調試此過程。通過設置'rc('verbose',level ='debug-annoying',fileo = sys.stdout)'我得到這個輸出:'MovieWriter - 命令標準輸出: '' MovieWriter - 命令標準錯誤號: '流映射:\ n Stream#0.0 - >#0.0 \ n按ctrl-c停止編碼\ nframe = 0 fps = 0 q = 0.0 Lsize = 0kB time = 10000000000.00 bitrate = 0.0kbits/s \ r \ nvideo:0kB audio: 0kB全局標題:0kB muxing開銷647.368421%' – astroMonkey 2014-10-30 15:49:34

回答

0

默認情況下,animation.MovieWriter使用subprocess.PIPE將幀饋送到寫入器。由於某些原因,使用multiprocessing時似乎不起作用。將最後一行更改爲 ani.save('foo.mp4', 'ffmpeg_file') 告訴作者在撰寫電影之前將幀暫時保存到光盤,這將側重解決問題。