python - How to sum contiguous nonzero elements within a numpy array -
here question
* value 2-d np.array(31 x 37) value 0,1.
it shows this:
only plot grid in blue color if value == 1
value_mask = np.ma.masked_less(value[:,:],0.001) pc =plt.pcolor(xx,yy,value_mask,alpha =1,facecolor = "pink",edgecolor = 'steelblue',zorder =3)
how sum amount of contiguous "blue grid".
in case, mean 1 upper right grid isolated majority ignored.
you can use scipy.ndimage.label
label contiguous regions in value
array, sum number of elements each label:
import numpy np scipy import ndimage value = np.array([[0, 0, 1, 1, 0, 0], [0, 0, 0, 1, 0, 0], [1, 1, 0, 0, 1, 0], [0, 0, 0, 1, 0, 0]]) # label contiguous regions of non-zero elements labels, nfeatures = ndimage.label(value) # sizes of each region sizes = (labels == (np.arange(nfeatures) + 1)[:, none, none]).sum((1, 2)) biggest = sizes.max() # number of non-zero elements in largest contiguous region print(biggest) # 3
Comments
Post a Comment