我有很多750x750圖像。我想從每幅圖像中獲取非重疊5x5塊的幾何平均值,然後對每幅圖像平均使用這些幾何平均值來爲每幅圖像創建一個特徵。我寫了下面的代碼,它似乎工作得很好。但是,我知道這不是很有效率。在300張左右的圖片上運行大約需要60秒。我有大約3000張圖片。所以,雖然它適用於我的目的,但效率並不高。我怎樣才能改進這個代碼?如何讓此代碼更快?
#each sublist of gmeans will contain a list of 22500 geometric means
#corresponding to the non-overlapping 5x5 patches for a given image.
gmeans = [[],[],[],[],[],[],[],[],[],[],[],[]]
#the loop here populates gmeans.
for folder in range(len(subfolders)):
just_thefilename, colorsourceimages, graycroppedfiles = get_all_images(folder)
for items in graycroppedfiles:
myarray = misc.imread(items)
area_of_big_matrix=750*750
area_of_small_matrix= 5*5
how_many = area_of_big_matrix/area_of_small_matrix
n = 0
p = 0
mylist=[]
while len(mylist) < how_many:
mylist.append(gmean(myarray[n:n+5,p:p+5],None))
n=n+5
if n == 750:
p = p+5
n = 0
gmeans[folder].append(my list)
#each sublist of mean_of_gmeans will contain just one feature per image, the mean of the geometric means of the 5x5 patches.
mean_of_gmeans = [[],[],[],[],[],[],[],[],[],[],[],[]]
for folder in range(len(subfolders)):
for items in range(len(gmeans[0])):
mean_of_gmeans[folder].append((np.mean(gmeans[folder][items],dtype=np.float64)))
可能是代碼審查合作伙伴網站的一個很好的候選人。不過,請確保先查看他們的網站規則。 – cel
對於這樣一個簡單的操作,這確實聽起來很慢(我認爲我的一些代碼計算高達4階累積量,更像直方圖均衡更快)。我會做的第一件事:嘗試[scikit-image](http://scikit-image.org/),它給你一個名爲[view_as_block]的函數(http://scikit-image.org/docs/stable/api /skimage.util.html#view-as-blocks)。這是由一些先進的numpy函數[as_strided]實現的(http://www.scipy-lectures.org/advanced/advanced_numpy/#example-fake-dimensions-with-strides)。我無法保證任何事情,但速度可能會更快! – sascha
代碼審查沒有太多的'numpy'流量;而「矢量化」是關於SO的常規問題。 CR對格式也很挑剔。 – hpaulj