title: How can I fill gaps in a binary image in OpenCV?
body: <p>I have some thresholded images of hand-drawn figures (circuits) but there are some parts where I need to have gaps closed between two points, as I show in the following image:</p>
  
  <p><a href="https://i.stack.imgur.com/EbuIW.png" rel="nofollow noreferrer">Binary image</a></p>
  
  <p>I tried closing (dilation followed by erosion), but it is not working. It doesn't fill the gaps and makes the resistors and other components unrecognizable. I couldn't find a proper value for the morph size and number of iterations that give me a good result without affecting the rest of the picture. It's important not to affect too much the components.
  I can't use hough lines because the gaps are not always in lines. </p>
  
  <p>Result after closing:</p>
  
  <p><a href="https://i.stack.imgur.com/UTAZP.png" rel="nofollow noreferrer">Result after closing</a></p>
  
  <pre><code>int morph_size1 = 2;
  Mat element1 = getStructuringElement(MORPH_RECT, Size(2 * morph_size1 + 1, 2 * morph_size1 + 1), Point(morph_size1, morph_size1));
  Mat dst1; // result matrix
  for (int i = 1; i&lt;3; i++)
  {
      morphologyEx(binary, dst1, CV_MOP_CLOSE, element1, Point(-1, -1), i);
  
  }
  
  imshow("closing ", dst1);
  </code></pre>
  
  <p>Any idea? 
  Thanks in advance. </p>