In opencv, how to get a list of sharded regions

I am working on a project where I want to evaluate some parameters in areas of a split image. So I have the following code

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

      

and now I would like to somehow get a list of masks by region in res. So for example if res is now something like this

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

      

I would like to get a result like

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

      

So this is a mask for each group of the same values ​​that are linked. Maybe this could somehow trigger the flood function? I can see that perhaps looping over each pixel and then filling the padding and comparing to see if this set of pixels can already be set might seem like very expensive, so is there something faster? Oh, and here is an example image res after running the code here

+3


source to share


1 answer


Here's one approach with 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

      



Example run -

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

      

+1


source







All Articles