python - Determine adjacent regions in numpy array -
i looking following. have numpy array labeled regions. numpy array represents segmented image. region number of adjacent cells same value. each region has own unique value. simplified version 3 regions 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 above example have 3 separate regions, each labeled unique value (1,2,3 in case).
what want value of adjacent (neighbor) regions each individual region. in case:
- region 1 adjacent region 2
- region 2 adjacent region 1 , 3
- region 3 adjacent region 2
what elegant , fastest way of achieving this?
many thanks!
i understand task return distinct entries of array adjacent given number (such 2). 1 way achieve numpy methods use roll shift given region 1 unit up, down, left, , right. logical or of shifted regions taken, , distinct elements match condition returned. remains remove region itself, since it's not considered own neighbor.
since roll
re-introduces values move beyond array's bounds @ opposite ends (which not desired here), additional step replace row or column false.
import numpy np x = np.array([[1, 1, 1], [1, 1, 2], [2, 2, 2], [3, 3, 3]], np.int32) region = 2 # number of region neighbors want y = x == region # convert boolean rolled = 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 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)
Comments
Post a Comment