1

Here is my question
* value is a 2-d np.array(31 x 37) with value 0,1.

It shows like this:

Only plot the grid in blue color if the 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)

enter image description here

How to sum the amount of the contiguous "blue grid".

In this case, I mean the 1 upper right grid isolated from the majority will be ignored.

0

1 Answer 1

3

You can use scipy.ndimage.label to label contiguous regions in your value array, then sum the number of elements for each label:

import numpy as np
from 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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.