Matplotlib:Live动画效果很好,但保存时显示空白打印

2024-10-01 13:41:43 发布

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

我做了一个森林火灾的小动画。我的密码在问题的最后。在

在我提问之前,这里有一些信息:

  • 没有树:forest[i,j] = 0
  • 一棵树:forest[i,j] = 1
  • 着火的树:forest[i,j] = 2

基本上,constructforest创建了一个二维数组,名为forest,大小为n,其树占用概率为p。之后setonfire点燃forest,而{}可以燃烧{}来扩大火势。在

当我用Python promptIPython prompt运行forestfire时,我得到了一个很好的动画,但是当我去检查我保存的视频文件时,我只看到一个空白的图。在

我做了一些研究,发现了很多关于这个问题的问题,但是我读到的建议都没有一个是有用的:

有人能告诉我发生了什么事吗?在

在森林火灾.py

from random import random

import numpy as np

import matplotlib.pylab as plt
import matplotlib.colors as mcolors
import matplotlib.animation as animation


def hazard(p):
    r=random()
    assert p>=0 and p<=1
    return r <= p


def constructforest(n,m,p):
    forest = np.zeros((n,n))
    for i in xrange(n):
        for j in xrange(m):
            if hazard(p):
                forest[i,j] = 1
    return forest


def setfire(forest,i,j):
    forest[i,j] = 2
    return forest


def spreadfire(forest):    

    n,m=forest.shape
    c = np.copy(forest)

    for i in xrange(n):
        for j in xrange(m):

            if c[i,j] == 1:

                Y, X = xrange(max(0,i-1),min(n,i+2)), xrange(max(0,j-1),min(m,j+2))

                for y in Y:
                    for x in X:

                        if c[y,x] == 2:
                            forest[i,j] = 2                        
    return forest


def canburn(forest):    

    n,m=forest.shape
    c = np.copy(forest)

    for i in xrange(n):
        for j in xrange(m):

            if c[i,j] == 1:

                Y, X = xrange(max(0,i-1),min(n,i+2)), xrange(max(0,j-1),min(m,j+2))

                for y in Y:
                    for x in X:

                        if c[y,x] == 2:
                            return True                      
    return False


def forestfire(forest):

    fig, ax = plt.subplots()

    movie = []    

    # Colormap
    red, green, blue = [(1,0,0,1)], [(0,1,0,1)], [(0,0,1,1)]   

    colors = np.vstack((blue, green, red))
    mycmap = mcolors.LinearSegmentedColormap.from_list('my_colormap', colors)

    # Initialization
    k = 0

    forest = spreadfire(forest)

    im = plt.imshow(forest, animated=True, cmap = mycmap, interpolation="none", origin='lower')
    movie.append([im])

    # Fire propagation
    while canburn(forest):
        k += 1
        print k

        forest = spreadfire(forest)

        im = plt.imshow(forest, animated=True, cmap = mycmap, interpolation="none", origin='lower')
        movie.append([im])

    return animation.ArtistAnimation(fig, movie, blit=True, repeat_delay=100)



ani = forestfire(setfire(constructforest(101,101,0.4),50,50))

ani.save("forestfire_test.mp4", writer = 'ffmpeg', fps=5, dpi=500)

编辑

根据@Y.Luo的@ImportanceOfBeingErnest在评论中的请求,我将matplotlib降级为2.0.0,并更改了动画的帧速率,但forestfire_test.mp4仍然显示空白图。在

以下是我的设置: enter image description hereenter image description here


Tags: inimportforreturnifmatplotlibdefas