If I understand the question correctly, then the approach can be turned upside down: if a pixel has pixels in its area that match the condition, increase it by one for each match. Do this for all pixels. Scipy (among others) offers image filtering tools:
In [51]: import scipy.ndimage
Create a sample image from a 1-dimensional array. Reshape creates a view instead of copying:
In [62]: I1d Out[62]: array([ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 129, 0, 129, 129, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 129, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 129]) In [63]: height Out[63]: 8 In [64]: width Out[64]: 8 In [65]: I = I1d.reshape((height, width)) In [66]: I Out[66]: array([[ 0, 0, 0, 0, 0, 0, 0, 0], [ 0, 0, 0, 0, 0, 0, 0, 0], [ 0, 0, 129, 0, 129, 129, 0, 0], [ 0, 0, 0, 0, 0, 0, 0, 0], [ 0, 0, 0, 0, 129, 0, 0, 0], [ 0, 0, 0, 0, 0, 0, 0, 0], [ 0, 0, 0, 0, 0, 0, 0, 0], [ 0, 0, 0, 0, 0, 0, 0, 129]])
Using convolution creates an image that contains increments for each pixel in the original from a binary pixel mask that exceeds the condition (here 128):
In [67]: scipy.ndimage.filters.convolve( (I > 128).astype(np.int), # conditioned binary image weights=np.array([[1, 1, 1], # each match weighted as 1 [1, 0, 1], [1, 1, 1]]), mode='constant', cval=0) # Use zeros as constant fill values on edges Out[67]: array([[0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 1, 2, 2, 2, 1, 0], [0, 1, 0, 2, 1, 1, 1, 0], [0, 1, 1, 3, 3, 3, 1, 0], [0, 0, 0, 1, 0, 1, 0, 0], [0, 0, 0, 1, 1, 1, 0, 0], [0, 0, 0, 0, 0, 0, 1, 1], [0, 0, 0, 0, 0, 0, 1, 0]]) In [68]: conv = _
If the ultimate goal is to add the original and increments:
In [69]: I + conv Out[69]: array([[ 0, 0, 0, 0, 0, 0, 0, 0], [ 0, 1, 1, 2, 2, 2, 1, 0], [ 0, 1, 129, 2, 130, 130, 1, 0], [ 0, 1, 1, 3, 3, 3, 1, 0], [ 0, 0, 0, 1, 129, 1, 0, 0], [ 0, 0, 0, 1, 1, 1, 0, 0], [ 0, 0, 0, 0, 0, 0, 1, 1], [ 0, 0, 0, 0, 0, 0, 1, 129]])
To output a 1-dimensional array, use ravel() or flatten() . The former creates a one-dimensional view of the original 2-dimensional array, the latter creates a flattened copy:
In [70]: conv.ravel() Out[70]: array([0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 2, 2, 2, 1, 0, 0, 1, 0, 2, 1, 1, 1, 0, 0, 1, 1, 3, 3, 3, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0])