I wish to locate the closest matching NxN block within a WxW window centred at location (x,y) of a larger 2D array. The code below works fine but is very slow for my needs as I need to run this operation many times.
Is there a better way to do this?
Here N = 3, W = 15, x =15, y = 15 and (bestx
, besty
) is the centre of the best matching block
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:
break
if cost < bestcost:
bestcost = cost
besty,bestx = Ywj,Ywi
print besty,bestx