Home > OS >  Extracting zones of ones in a binary numpy array
Extracting zones of ones in a binary numpy array

Time:05-06

I'm looking for a way to extract zones of ones in a binary numpy array to put different values, for instance, for the following array:

x=[[0,1,1,0,0,0],
   [0,1,1,0,0,0],
   [0,1,0,0,0,0],
   [0,0,0,1,1,0],
   [0,0,1,1,1,0],
   [0,0,0,0,0,0]]

Expected result:

x=[[0,2,2,0,0,0],
   [0,2,2,0,0,0],
   [0,2,0,0,0,0],
   [0,0,0,3,3,0],
   [0,0,3,3,3,0],
   [0,0,0,0,0,0]]

CodePudding user response:

Use scipy.ndimage.label:

x=[[0,1,1,0,0,0],
   [0,1,1,0,0,0],
   [0,1,0,0,0,0],
   [0,0,0,1,1,0],
   [0,0,1,1,1,0],
   [0,0,0,0,0,0]]

a = np.array(x)

from scipy.ndimage import label
b = label(a)[0]

output:

# b
array([[0, 1, 1, 0, 0, 0],
       [0, 1, 1, 0, 0, 0],
       [0, 1, 0, 0, 0, 0],
       [0, 0, 0, 2, 2, 0],
       [0, 0, 2, 2, 2, 0],
       [0, 0, 0, 0, 0, 0]], dtype=int32)

to start labeling from 2:

b = (label(a)[0] 1)*a

output:

array([[0, 2, 2, 0, 0, 0],
       [0, 2, 2, 0, 0, 0],
       [0, 2, 0, 0, 0, 0],
       [0, 0, 0, 3, 3, 0],
       [0, 0, 3, 3, 3, 0],
       [0, 0, 0, 0, 0, 0]])
  • Related