title: How to extract the largest connected component using OpenCV and Python?
body: <p>I am using OpenCV in Python to be able to identify only the Leaf presented on the image. I already be able to segment my image, and now I am currently stuck at "how to crop the largest component after I have detected all of them. Below is the codes, please have a look.</p>
  
  <ol>
  <li><p>Using scipy.ndimage, I was unable to advance after find the components:</p>
  
  <pre><code>def undesired_objects ( image ):
      components, n = ndimage.label( image )
      components = skimage.morphology.remove_small_objects( components, min_size = 50 )
      components, n = ndimage.label( components )
      plot.imshow( components )
      plot.show()
  </code></pre></li>
  <li><p>Using OpenCV connectedComponentsWithStats:</p>
  
  <pre><code>def undesired_objects ( image ):
      image = image.astype( 'uint8' )
      nb_components, output, stats, centroids = cv2.connectedComponentsWithStats(image, connectivity=4)
      sizes = stats[1:, -1]; nb_components = nb_components - 1
      min_size = 150
      img2 = np.zeros(( output.shape ))
      for i in range(0, nb_components):
          if sizes[i] &gt;= min_size:
              img2[output == i + 1] = 255
              plot.imshow( img2 )
              plot.show()
  </code></pre></li>
  </ol>
  
  <p>However, in both approaches, I'm still getting more than one component as result. Below, you will find the binary image:</p>
  
  <p><a href="https://i.stack.imgur.com/Mlmyx.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Mlmyx.png" alt="Binary Image"></a></p>