I have following cells:
cells = np.array([[1, 1, 1],
[1, 1, 0],
[1, 0, 0],
[1, 0, 1],
[1, 0, 0],
[1, 1, 1]])
and I want to calculate horizontal and vertical adjacencies to come to this result:
# horizontal adjacency
array([[3, 2, 1],
[2, 1, 0],
[1, 0, 0],
[1, 0, 1],
[1, 0, 0],
[3, 2, 1]])
# vertical adjacency
array([[6, 2, 1],
[5, 1, 0],
[4, 0, 0],
[3, 0, 1],
[2, 0, 0],
[1, 1, 1]])
The actual sollution looks like this:
def get_horizontal_adjacency(cells):
adjacency_horizontal = np.zeros(cells.shape, dtype=int)
for y in range(cells.shape[0]):
span = 0
for x in reversed(range(cells.shape[1])):
if cells[y, x] > 0:
span += 1
else:
span = 0
adjacency_horizontal[y, x] = span
return adjacency_horizontal
def get_vertical_adjacency(cells):
adjacency_vertical = np.zeros(cells.shape, dtype=int)
for x in range(cells.shape[1]):
span = 0
for y in reversed(range(cells.shape[0])):
if cells[y, x] > 0:
span += 1
else:
span = 0
adjacency_vertical[y, x] = span
return adjacency_vertical
The Algorithm is basically (for horizontal adjacency):
- loop throgh rows
- loop backward throgh columns
- if the x, y value of cells is not zero, add 1 to the actual span
- if the x, y value of cells is zero, reset actual span to zero
- set the span as new x, y value of the resulting array
Since I need to loop two times over all array elements this is slow for bigger arrays (e.g. images).
Is there a way to improve the algorithm using vectorization or some other numpy magic?
Summary:
Great suggestions have been made by joni and Mark Setchell!
I created a small Repo with a sample image and a python file with the comparisons. The results are astonishing:
- Original Approach: 3.675 s
- Using Numba: 0.002 s
- Using Cython: 0.005 s

