import numpy
import scipy.signal
a = numpy.zeros((6, 6), dtype=numpy.int)
a[2:4, 2:4] = 1
a[2, 4] = 1
b = 1 - a
c = scipy.signal.convolve2d(b, numpy.ones((3, 3)), mode='same')
print(numpy.sum(c * a))
Counting of adjacent cells in a numpy array