2017-08-15 68 views
1

我有一個4D numpy數組,考慮第4維度是「時間」維度。連續幀被繪製爲2D熱圖,使用前兩個維度 - 您正在獲取「動畫」。在測量執行時間時,我獲得了26幀的16秒,這很低。我如何加快下面代碼的執行時間?我寧願使用Seaborn創建熱圖,而不是matplotlib(儘管它是後者的擴展)。Seaborn Heatmap繪圖執行時間優化

import numpy as np 
import matplotlib.pyplot as plt 
import seaborn as sns 
import time 

data = np.load('data.npy') 

fig = plt.figure() 
ax = fig.add_subplot(111) 
im = sns.heatmap(np.zeros((256, 128)), cmap = 'viridis', vmin = 0, vmax = 90) 
plt.show(block = False) 

start = time.time() 
for i in range (0, data[0, 0, 0, :].size): 
    plt.clf() 
    sns.heatmap(20*np.log10(abs(data[:, :, 2, i])), cmap = 'viridis', vmin = 0, vmax = 90) 
    fig.canvas.draw() 
end = time.time() 

print(end - start) 
+0

如何預先計算:'20 * np.log10( np.abs(data))'在進入循環之前使用那些沒有涉及計算的循環內部? – Divakar

+0

好主意 - 它改善了大約4秒 - 現在在11.7秒內顯示26幀。一些數據:https://drive.google.com/open?id=0B6ksYqU-Jy7sRkczaVBLS3NuOUU –

+0

我需要大約12.5Hz的幀率 - 這個數據集的總體顯示時間應該是大約2-3秒。 –

回答

1

下面的代碼產生完全相同的情節作爲seaborn,但快10倍(執行時間=約2秒):

import numpy as np 
import matplotlib.pyplot as plt 
import matplotlib.animation as animation 
from mpl_toolkits.axes_grid1 import make_axes_locatable 
import time 

data = np.load('data.npy') 
data = 20*np.log10(abs(data)) 

fig = plt.figure(figsize = (7, 7)) 
ax = fig.add_subplot(111) 

#initialise subfigure (dimensions and parameters) 
im = ax.imshow(np.zeros((256, 128)), cmap = 'viridis', vmin = 0, vmax = 90, interpolation = 'none', aspect = 'auto') 

#get rid of spines and fix range of axes, rotate x-axis labels 
ax.spines['left'].set_visible(False) 
ax.spines['right'].set_visible(False) 
ax.spines['top'].set_visible(False) 
ax.spines['bottom'].set_visible(False) 
ax.xaxis.set_ticks_position('bottom') 
ax.yaxis.set_ticks_position('left') 
ax.xaxis.set_ticks(np.arange(0, 128, 5)) 
ax.yaxis.set_ticks(np.arange(0, 256, 10)) 
for tick in ax.get_xticklabels(): 
    tick.set_rotation(90) 

#use a divider to fix the size of the colorbar 
divider = make_axes_locatable(ax) 
#colorbar on the right of ax. Colorbar width in % of ax and space between them is defined by pad in inches 
cax = divider.append_axes('right', size = '5%', pad = 0.07) 
cb = fig.colorbar(im, cax = cax) 
#remove colorbar frame/spines 
cb.outline.set_visible(False) 

#don't stop after each subfigure change 
plt.show(block = False) 

#loop through array 
start = time.time() 
for i in range(data[0, 0, 2, :].size): 
    time.sleep(0.005) 
    im.set_array(data[:, :, 0, i]) 
    fig.canvas.draw() 
stop = time.time() 
print(stop-start)