2017-03-15 83 views
0

可以使jupyter筆記本中的圖像對生成動畫?如何使用子圖中的圖像生成動畫(matplotlib)

帶圖像的兩個列表:

greys = io.imread_collection(path_greys) 
grdTru= io.imread_collection(path_grdTru) 

以下天真代碼失敗以產生動畫:

for idx in range(1,900): 
    plt.subplot(121) 
    plt.imshow(greys[idx], interpolation='nearest', cmap=plt.cm.gray) 
    plt.subplot(122) 
    plt.imshow(grdTru[idx], interpolation='nearest', cmap=plt.cm.,vmin=0,vmax=3) 
    plt.show() 

(它產生副區的列表)

順便提及,如果粘貼在筆記本中,則example found in matplotlib文檔失敗。

回答

2

爲了使在jupyter筆記本the example工作,你需要包括

%matplotlib notebook 

魔法命令。

import numpy as np 
%matplotlib notebook 
import matplotlib.pyplot as plt 
import matplotlib.animation as animation 

fig = plt.figure() 


def f(x, y): 
    return np.sin(x) + np.cos(y) 

x = np.linspace(0, 2 * np.pi, 120) 
y = np.linspace(0, 2 * np.pi, 100).reshape(-1, 1) 

im = plt.imshow(f(x, y), animated=True) 


def updatefig(*args): 
    global x, y 
    x += np.pi/15. 
    y += np.pi/20. 
    im.set_array(f(x, y)) 
    return im, 

ani = animation.FuncAnimation(fig, updatefig, interval=50, blit=True) 
plt.show() 

然後,您可以很容易地將它調整到您的圖像列表。

從matplotlib 2.1版本開始,您也可以選擇內嵌創建JavaScript動畫。

from IPython.display import HTML 
HTML(ani.to_jshtml()) 

完整的示例:

import numpy as np 
%matplotlib inline 
import matplotlib.pyplot as plt 
import matplotlib.animation as animation 

def f(x, y): 
    return np.sin(x) + np.cos(y) 

x = np.linspace(0, 2 * np.pi, 120) 
y = np.linspace(0, 2 * np.pi, 100).reshape(-1, 1) 

im = plt.imshow(f(x, y), animated=True); 


def updatefig(*args): 
    global x, y 
    x += np.pi/15. 
    y += np.pi/20. 
    im.set_array(f(x, y)) 
    return im, 

ani = animation.FuncAnimation(fig, updatefig, interval=50, blit=True) 

from IPython.display import HTML 
HTML(ani.to_jshtml())