提取二进制 numpy 数组中的区域

Extracting zones of ones in a binary numpy array

我正在寻找一种方法来提取二进制 numpy 数组中的区域以放置不同的值,例如,对于以下数组:

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]]

预期结果:

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]]

使用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]

输出:

# 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)

从 2:

开始标注
b = (label(a)[0]+1)*a

输出:

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]])