I have following 2D array
regions = array([[3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4],
[3, 3, 3, 3, 8, 8, 8, 8, 8, 4, 4, 4, 4],
[3, 3, 3, 3, 8, 8, 8, 8, 8, 4, 4, 4, 4],
[3, 3, 3, 3, 8, 8, 8, 8, 8, 4, 4, 4, 4],
[3, 6, 6, 6, 8, 8, 8, 8, 8, 7, 7, 7, 4],
[3, 6, 6, 6, 8, 8, 8, 8, 8, 7, 7, 7, 4],
[3, 6, 6, 6, 6, 8, 8, 8, 7, 7, 7, 7, 4],
[3, 6, 6, 6, 6, 2, 2, 2, 7, 7, 7, 7, 4],
[5, 6, 6, 6, 6, 2, 2, 2, 7, 7, 7, 7, 1],
[5, 6, 6, 6, 6, 2, 2, 2, 7, 7, 7, 7, 1],
[5, 6, 6, 6, 6, 2, 2, 2, 7, 7, 7, 7, 1],
[5, 5, 5, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1],
[5, 5, 5, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1]])
I want to find neighbouring numbers for all individual numbers. For example 3
is a negibour of 4,5,6,8
. Currently i am doing this excercise using a for loop
by following below mentioned code.
numbers = scipy.unique(regions)
for i in numbers:
index = i-1
slices = scipy.ndimage.find_objects(regions)
sub_im = regions[slices[index]]
im = sub_im == i
neighbors = scipy.ndimage.binary_dilation(input=im, structure=disk(1))
neighbors = neighbors*sub_im
neighbors_list = scipy.unique(neighbors)[1:] - 1
print (neighbors_list)
The problem is I dont want to use for loop as my regions array is in the order of millions. Is there any fast way to solve this problem without for loop?