下面的代码始终显示空白图像
%matplotlib tk
import numpy as np
import matplotlib.pyplot as pp
import time
from copy import deepcopy
pp.close('all')
img1 = np.zeros((400,400), dtype = np.uint8)
new_list = []
for i in range(100):
new_list.append(deepcopy(img1).astype(np.uint8))
new_list[-1][i:i+100,i:i+100] = 255
if i == 0:
new_list[-1][i:i+100,i:i+100] = 0
#new_list[-1][i,i] = 1
if True:
fig,ax = pp.subplots(1,1)
image = ax.imshow(new_list[0],animated=True)
fig.canvas.draw()
start = time.time()
tic = start
for i in range(100):
if not(i % 10):
toc = time.time()
tic = time.time()
image.set_data(new_list[i])
fig.canvas.draw()
但是,如果我只是取消注释单行
new_list[-1][i,i] = 1
或以任何其他非零图像开头,例如
image = ax.imshow(np.eye(400, dtype = np.uint8),animated=True)
应有的图形更新-显示移动100x100正方形。我的问题是:为什么会发生这种情况?如果从仅零图像开始,有什么方法可以使图形更新起作用?
答案 0 :(得分:1)
如果图像中的初始数组全为零,则即使更新图像也将是单色的。为避免这种情况,您可以为图像设置规格化,然后将其整个使用。在这种情况下,最大值似乎是255,因此
ax.imshow(..., vmin=0, vmax=255)
在您的情况下,可以使用FuncAnimation
:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
from copy import deepcopy
img1 = np.zeros((400,400), dtype = np.uint8)
new_list = []
for i in range(100):
new_list.append(deepcopy(img1).astype(np.uint8))
new_list[-1][i:i+100,i:i+100] = 255
if i == 0:
new_list[-1][i:i+100,i:i+100] = 0
new_list[-1][i,i] = 1
fig,ax = plt.subplots(1,1)
image = ax.imshow(new_list[0],animated=True, vmin=0, vmax=255)
def animate(i):
image.set_data(new_list[i])
ani = FuncAnimation(fig, animate, frames=100, interval=10)
plt.show()