在 opencv 中,我如何获得分段区域列表

In opencv how do I get a list of segemented regions

我正在做一个项目,我想评估分割图像区域的某些参数。所以我有以下代码

  col = cv2.imread("in.jpg",1)
  col=cv2.resize(col,(width,height),interpolation=cv2.INTER_CUBIC)
  res=cv2.pyrMeanShiftFiltering(col,20,45,3)

现在想以某种方式获得 res 中每个区域的掩码列表。 因此,例如,如果 res 现在是这样的

1 1 0 2 1 
1 0 0 2 1
0 0 2 2 1

我想得到这样的输出

1 1 0 0 0
1 0 0 0 0
0 0 0 0 0
,
0 0 1 0 0 
0 1 1 0 0
1 1 0 0 0
,
0 0 0 1 0 
0 0 0 1 0
0 0 1 1 0
,
0 0 0 0 1 
0 0 0 0 1
0 0 0 0 1

所以这是每组连接的相同值的掩码。也许这会以某种方式涉及 floodfill 功能?我可以 看到可能通过遍历每个像素然后进行填充并比较以查看是否已经设置了该组像素可能会起作用,但这似乎是一种非常昂贵的方法所以有更快的方法吗? 哦,这是代码 运行 后 res 的示例图像

这是 cv2.connectedComponents -

的一种方法
def list_seg_regs(a): # a is array
    out = []
    for i in np.unique(a):
        ret, l = cv2.connectedComponents((a==i).astype(np.uint8))
        for j in range(1,ret):
            out.append((l==j).astype(int)) #skip .astype(int) for bool
    return out

样本运行-

In [53]: a = np.array([
    ...:    [1, 1, 0, 2, 1],
    ...:    [1, 0, 0, 2, 1],
    ...:    [0, 0, 2, 2, 1]])

In [54]: out = list_seg_regs(a)

In [55]: out[0]
Out[55]: 
array([[0, 0, 1, 0, 0],
       [0, 1, 1, 0, 0],
       [1, 1, 0, 0, 0]])

In [56]: out[1]
Out[56]: 
array([[1, 1, 0, 0, 0],
       [1, 0, 0, 0, 0],
       [0, 0, 0, 0, 0]])

In [57]: out[2]
Out[57]: 
array([[0, 0, 0, 0, 1],
       [0, 0, 0, 0, 1],
       [0, 0, 0, 0, 1]])

In [58]: out[3]
Out[58]: 
array([[0, 0, 0, 1, 0],
       [0, 0, 0, 1, 0],
       [0, 0, 1, 1, 0]])