Filtering elements of a numpy array depending on their occurrences

Viewed 42

i have the following 2D numpy array M

M = np.array([[1,1,1,0,0,0,0,0,0,0,0],
              [1,1,1,0,0,0,0,0,0,1,1],
              [1,1,1,0,0,0,0,0,0,1,1],
              [0,0,0,0,0,1,1,1,0,0,0],
              [0,0,0,0,0,1,1,1,0,0,0],
              [1,1,1,0,1,1,1,1,0,0,0],
              [1,1,1,0,0,1,1,1,0,0,0],
              [1,1,1,0,0,1,1,1,0,0,0]])

which I want to identify its spots (Pixels with value==1 and connected to each other).

Thanks to the function 'label' from scipy, I can identify all of my spots in the matrix. The output should seem like this:

Output, Nbr= label(M)
#Output=  array([[1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0],
#                [1, 1, 1, 0, 0, 0, 0, 0, 0, 2, 2],
#                [1, 1, 1, 0, 0, 0, 0, 0, 0, 2, 2],
#                [0, 0, 0, 0, 0, 3, 3, 3, 0, 0, 0],
#                [0, 0, 0, 0, 0, 3, 3, 3, 0, 0, 0],
#                [4, 4, 4, 0, 3, 3, 3, 3, 0, 0, 0],
#                [4, 4, 4, 0, 0, 3, 3, 3, 0, 0, 0],
#                [4, 4, 4, 0, 0, 3, 3, 3, 0, 0, 0]])

I want only to have spots with 9 elements, that means the first and fourth spot.

using a for loop like this works fine:

for i in range(Nbr+1):
    Spot= np.argwhere(components[:,:]== i)
    if len(Spot)!=9:
        M[Spot[:, 0], Spot[:, 1]]=0
#M=  array([[1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0],
#           [1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0],
#           [1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0],
#           [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
#           [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
#           [1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0],
#           [1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0],
#           [1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0]])

The porblem is when my Spots are more than 4, my code is slower.

Is there any faster alternative that can do the job of the for loop?

Thanks.

0 Answers
Related