I am looking for the following. I have a numpy array which is labeled as regions. The numpy array represents a segmented image. A region is a number of adjacent cells with the same value. Each region has its own unique value. A simplified version with 3 regions would look like this:
x = np.array([[1, 1, 1], [1, 1, 2], [2, 2, 2], [3, 3, 3]], np.int32)
output:
array([[1, 1, 1],[1, 1, 2],[2, 2, 2],[3, 3, 3]])
In the above example we have 3 separate regions, each labeled with an unique value (1,2,3 in this case).
What I want is the value of adjacent (neighbor) regions for each individual region. So in this case:
- Region 1 is adjacent to region 2
- Region 2 is adjacent to region 1 and 3
- Region 3 is adjacent to region 2
What would be the most elegant and fastest way of achieving this?
Many thanks!
I understand that the task is to return all distinct entries of the array that are adjacent to a given number (such as 2). One way to achieve this with NumPy methods is to use roll to shift the given region by one unit up, down, left, and right. The logical OR of the shifted regions is taken, and all distinct elements that match this condition are returned. It then remains to remove the region itself, since it's not considered its own neighbor.
Since roll
re-introduces the values that move beyond array's bounds at the opposite ends (which is not desired here), an additional step is to replace this row or column with False.
import numpy as npx = np.array([[1, 1, 1], [1, 1, 2], [2, 2, 2], [3, 3, 3]], np.int32)
region = 2 # number of region whose neighbors we wanty = x == region # convert to Booleanrolled = np.roll(y, 1, axis=0) # shift down
rolled[0, :] = False
z = np.logical_or(y, rolled)rolled = np.roll(y, -1, axis=0) # shift up
rolled[-1, :] = False
z = np.logical_or(z, rolled)rolled = np.roll(y, 1, axis=1) # shift right
rolled[:, 0] = False
z = np.logical_or(z, rolled)rolled = np.roll(y, -1, axis=1) # shift left
rolled[:, -1] = False
z = np.logical_or(z, rolled)neighbors = set(np.unique(np.extract(z, x))) - set([region])
print(neighbors)