title: Closing gaps in objects of opencv mask
body: <p>I've computed the following mask of an image containing corn:
  <a href="https://i.stack.imgur.com/xpme0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xpme0.png" alt="enter image description here" /></a></p>
  <p>the problem is, now i have black parts inside the seeds. Is there a way to get rid of them while making sure that seeds remain disconnected from each other?</p>
  <hr />
  <p>My ultimate goal is to count the seeds on the picture, using watershed algorithm. I observed when the seeds are touching each other, it introduces a imprecision to the algorithm, so I tried to introduce gaps between seeds by using canny and subtracting the borders from the mask, which is the result above.</p>
  <p>My code so far:</p>
  <pre><code>auto img = GetAreaOfInterest(orig, bt); // &lt;- just a Gauss blur with OTSU thresh
  {
      cv::Mat gray, edges;
      cv::cvtColor(orig, gray, cv::COLOR_BGR2GRAY);
      // tried bilateralFIlter here, but things only got worse
  
      cv::Canny(gray, edges, 40, 160);
      cv::dilate(edges, edges,
                 cv::getStructuringElement(cv::MORPH_ELLIPSE, {5, 5}),
                 {-1, -1}, 1);
  
      img.setTo(0, edges != 0); 
  }
  
  cv::Mat background, foreground, unknown, markers;
  cv::dilate(img, background,
             cv::getStructuringElement(cv::MORPH_ELLIPSE, {3,3}));
  
  /* Get area for which we are sure it's the foreground */
  cv::distanceTransform(img, img, cv::DIST_L1, 3, CV_8U);
  {
      double max;
      cv::minMaxLoc(img, nullptr, &amp;max);
      cv::threshold(img, img, 0.46 * max, 255, cv::THRESH_BINARY);
  
  }
  img.convertTo(foreground, CV_8UC3);
  show_resized(&quot;distance&quot;, foreground, 0.5);
  
  /* Mark unknown areas */
  cv::subtract(background, foreground, unknown);
  
  /* Set up markers */
  cv::connectedComponents(foreground, markers);
  markers = markers + 1;
  markers.setTo(0, unknown == 255);
  
  /* Expand markers */
  cv::watershed(orig, markers);
  
  // Count objects
  </code></pre>
  <p>original image:
  <a href="https://i.stack.imgur.com/p16TF.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/p16TF.jpg" alt="enter image description here" /></a></p>
  <p>the most problematic image:
  <a href="https://i.stack.imgur.com/YIeKn.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YIeKn.jpg" alt="enter image description here" /></a></p>