Numpy / Scipy Connected Components
I am writing a python program to find "islands" 1s, 0s or -1s in an L * L matrix. I need This to find these "areas" of related components, mark each one and be able to return for a given element of the matrix m [ x] [y], the size of the island to which it belongs.
import numpy as np
from scipy import ndimage
from scipy import misc
import matplotlib.pyplot as plt
m = np.random.randint(-1,2,(L,L))
mask1 = (m == -1)
mask2 = (m == 0)
mask3 = (m == 1)
label_m1, nb_labels1 = ndimage.label(mask1)
label_m2, nb_labels2 = ndimage.label(mask2)
label_m3, nb_labels3 = ndimage.label(mask3)
This should give me labeled islands for a random matrix m (just an example), but I don't know how to get the size of the "area" that a given point belongs to. Could you help me? I have almost no programming experience, so forgive me if the question is stupid.
thank
+3
albertociarr
source
to share
1 answer
Something like:
label_count_m1 = np.bincount(label_m1.ravel())
label_count_m1[0] = 0
sizes_m1 = label_count_m1[label_m1]
+2
user2379410
source
to share