title: Connected component labeling in Emgu / Opencv
body: <p>I've been look ing for a method for connected component labeling in Emgu (c# wrapper for OpenCV). I've failed to find a direct method for such a basic CV strategy. However, I did come across many suggestions for doing it using FindContours and DrawContours but without code examples. So I had a go at it and it seems to work okay.</p>
  
  <p>I'm dropping it here for two reasons. </p>
  
  <ol>
  <li>So people searching for it can find a code example. </li>
  <li>More importantly, i'm wondering if there are suggestions for optimization and improvements of this function. E.g. is the chain approximation method for FindContours efficient/appropriate? </li>
  </ol>
  
  <pre class="lang-cs prettyprint-override"><code>    public static Image&lt;Gray, byte&gt; LabelConnectedComponents(this Image&lt;Gray, byte&gt; binary, int startLabel)
      {
          Contour&lt;Point&gt; contours = binary.FindContours(
              CHAIN_APPROX_METHOD.CV_CHAIN_APPROX_NONE, 
              RETR_TYPE.CV_RETR_CCOMP);
  
          int count = startLabel;
          for (Contour&lt;Point&gt; cont = contours;
                      cont != null;
                      cont = cont.HNext)
          {
              CvInvoke.cvDrawContours(
              binary,
              cont,
              new MCvScalar(count),
              new MCvScalar(0),
              2,
              -1,
              LINE_TYPE.FOUR_CONNECTED,
              new Point(0, 0));
              ++count;
          }
          return binary;
      }
  </code></pre>