阅读许多文件并创建animationpython

2024-06-01 20:40:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我写了脚本,从fits文件创建动画(电影)。一个文件的大小为2.8 MB,文件数为9000个。 这是密码

import numpy as np
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import os
import pyfits
import glob
import re



Writer = animation.writers['ffmpeg']
writer = Writer(fps=15, metadata=dict(artist='Me'), bitrate=1800)

global numbers
numbers=re.compile(r'(\d+)')

def numericalSort(value):
    parts = numbers.split(value)
    parts[1::2] = map(int, parts[1::2])
    return parts


image_list=glob.glob('/kalib/*.fits')

image_list= sorted(image_list,key=numericalSort)
print image_list
fig = plt.figure("movie")
img = []

for i in range(0,len(image_list)):

    hdulist = pyfits.open(image_list[i])
    im = hdulist[0].data
    img.append([plt.imshow(im,cmap=plt.cm.Greys_r)])


ani = animation.ArtistAnimation(fig,img, interval=20, blit=True,repeat_delay=0)
ani.save('movie.mp4', writer=writer)

我想我的问题是当我创建数组img[]时,我有8gb的RAM,当RAM满了,我的操作系统终止python脚本。在

我的问题是: 如何读取9000个文件并创建动画?是否可以创建一些缓冲区或一些并行处理?在

有什么建议吗?在


Tags: 文件imageimport脚本imgmatplotlibasplt
2条回答

我建议您使用ffmpeg。使用image2pipe命令,您不必将所有图像加载到RAM中,而是逐个(我认为)加载到管道中。

除此之外,ffmpeg允许您操作视频(帧速率、编解码器、格式等)。在

https://ffmpeg.org/ffmpeg.html

使用FuncAnimation而不是ArtistAnimation创建动画可能更好,如ArtistAnimation vs FuncAnimation matplotlib animation matplotlib.animation中所述,FuncAnimation在内存使用方面更有效。您可能还想尝试FuncAnimation的save_count参数,请查看API文档中的示例。在

相关问题 更多 >