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 blockimport numpy as np## Generate some test dataCurPatch = np.random.randint(20, size=(3, 3))Data = np.random.randint(20,size=(30,30))# Current Location x,y = 15,15# Initialise Best Matchbestcost = 999.0bestx = 0;besty=0for 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,Ywiprint besty,bestx
Finding the best matching block/patch in Python
python;array;search