我希望能够在一个较大的二维数组中,找到以位置(x,y)为中心、大小为WxW的窗口内最接近的NxN块。下面的代码可以工作,但对于我的需求来说非常慢,因为我需要多次运行此操作。有更好的方法吗?这里N=3,W=15,x=15,y=15,(bestx,besty)是最佳匹配块的中心。
import numpy as np
## Generate some test data
CurPatch = np.random.randint(20, size=(3, 3))
Data = np.random.randint(20,size=(30,30))
# Current Location
x,y = 15,15
# Initialise Best Match
bestcost = 999.0
bestx = 0;besty=0
for Wy in xrange(-7,8):
for Wx in xrange(-7,8):
Ywj,Ywi = y+Wy,x+Wx
cost = 0.0
for py in xrange(3):
for px in xrange(3):
cost += abs(Data[Ywj+py-1,Ywi+px-1] - CurPatch[py,px])
if cost < bestcost:
bestcost = cost
besty,bestx = Ywj,Ywi
print besty,bestx
for px in xrange(3):
中检查cost
是否大于或等于bestcost
,如果是,你可以使用break
来跳出循环,这样可以节省很多不必要的迭代。 - Kobi K