title: Counting the number of components/objects in an array
body: <p>I am wondering what is a good way to count the number of components in a matrix. Let's say that ones constitute a component and zeros constitute the background. So in the array below there are 4 components:</p>
  <pre class="lang-py prettyprint-override"><code>a = np.array([
      [1,1,0,0,0,0,0,0],
      [1,1,1,0,0,0,1,0],
      [0,1,0,0,0,1,1,1],
      [0,0,0,0,0,1,1,1],
      [0,1,0,0,0,0,1,0],
      [0,0,0,1,1,0,0,0],
      [0,0,1,1,0,0,0,0]])
  </code></pre>
  <p>I know that I can do this with Scipy like this:</p>
  <pre class="lang-py prettyprint-override"><code>from scipy.ndimage import label
  
  labeled_array, num_features = label(a)
  </code></pre>
  <p>where <code>num_features</code> will give me the correct answer of 4.</p>
  <p>How would I implement this myself? I am asking what the correct technique would be. Preferably I want to implement this with matrix operations (e.g. a Numpy solution). So no for-loops where I am checking every value individually.</p>
  <p>I am asking this because in the end I want to implement the solution in Tensorflow such that the whole thing is differentiable. This way I can add the number of components as a term in my loss function for an image segmentation problem, which is my end goal.</p>
  <p>I thought of using morphological erosion, to shrink the components in the matrix until only 1s remain. Then I could just take the sum of the array to count the number of components. Unfortunately if I erode an isolated one <code>[[0,0,0],[0,1,0],[0,0,0]]</code> it will remove it (<code>[[0,0,0],[0,0,0],[0,0,0]]</code>). If I repeat erosion it will continue until there are no components left. I also think I could use skeletonization, which garantuees that there would always remain a center-point? But I am not sure if that is the right technique, and how I would implement that.</p>
  <p>I was wondering if anyone has any ideas on this problem or knows how to solve it. Any input would be greatly appreciated!</p>