我试图在python中进行森林火灾模拟,我很难将其显示为动画。我的代码是
import numpy as np
from Lib import random
import matplotlib.pyplot as plt
import matplotlib.animation as animation
class Forest:
def __init__(self, width, height):
self.width = width
self.height = height
self.trees = np.zeros((self.height, self.width, 3), dtype=np.float32)
self.images = []
def simulate(self, iterations):
for i in range(iterations):
for j in range(self.height):
for k in range(self.width):
#some logic goes here
self.images.append(plt.imshow(self.trees / 255, animated=True))
def update_fig(self, j):
global im
im = self.images[j]
return im
f = 0.000005
p = 0.01
forest = Forest(100, 100)
forest.simulate(500)
fig = plt.figure()
im = forest.images[0]
ani = animation.FuncAnimation(fig, forest.update_fig, interval=50, blit=True)
plt.show()
然而,使用此代码我得到了一个 ' AxesImage' object不可迭代错误。我认为问题在于 update_fig 功能,我只是不知道究竟是什么导致它
答案 0 :(得分:1)
情节需要是可迭代的。如果您将[ ]
放在此行中:
self.images.append(plt.imshow(self.trees / 255, animated=True))
到self.images.append([plt.imshow(self.trees / 255, animated=True)])
它应该工作。 其他相关点是您似乎正在使用3D阵列。我不确定这些是否适用于浮点类型。将它们更改为。uint8
并确保您的数组是RGB颜色三元组
编辑:正如@ImportanceOfBeingErnest所提到的,这确实适用于float数组。做了一个糟糕的假设。
这些是我推荐的更改(我已将注释放在需要您注意的行中):
import numpy as np
from Lib import random
import matplotlib.pyplot as plt
import matplotlib.animation as animation
class Forest:
def __init__(self, width, height):
self.width = width
self.height = height
self.trees = np.zeros((self.height, self.width, 3), dtype=np.uint8) #uint since you are using 3D arrays
self.images = []
def simulate(self, iterations):
# for i in range(iterations):
# for j in range(self.height):
# for k in range(self.width):
# #some logic goes here
for i in range(iterations):
self.trees = np.random.randint(0, 255, (self.height, self.width, 3), dtype=np.uint8)
self.images.append([plt.imshow(self.trees / 255, animated=True)]) # add the [] since it needs to be iterable
def update_fig(self, j):
global im
im = self.images[j]
return im
f = 0.000005
p = 0.01
forest = Forest(100, 100)
forest.simulate(500)
fig = plt.figure()
im = forest.images[0]
ani = animation.FuncAnimation(fig, forest.update_fig, interval=50, blit=True)
plt.show()