簡體   English   中英

使用多處理時python matplotlib動畫保存錯誤

[英]python matplotlib animation save error when using multiprocessing

我正在創建一個matplotlib動畫,該動畫遍歷文件中的一系列圖像。 我正在可視化的文件通常很大,並且每個圖像堆棧都有相當長的加載時間(〜5秒)。 通過使加載過程與多處理過程錯開,我設法使動畫順利運行,但是我無法將動畫另存為視頻文件。

這是代碼:

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一起播放?

默認情況下animation.MovieWriter使用subprocess.PIPE將幀饋送到編寫器。 當出於某種原因使用multiprocessing時,這似乎不起作用。 將最后一行更改為ani.save('foo.mp4', 'ffmpeg_file')告訴編寫者在制作電影之前將幀臨時保存到光盤中,這ani.save('foo.mp4', 'ffmpeg_file')問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM