我有很多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