title: Improving circle detection
body: <p>I am trying to detect circles in my images. I have written the following code in C# using EmguCV. Most of the times it works, but there are some cases that it detects smaller or larger circles that are slightly shifted to a side. </p>
  
  <p>Here is my code:</p>
  
  <pre><code>        Thread.Sleep(1000);
          imgCrp.Save(DateTime.Now.ToString("yyMMddHHmmss") + ".jpg");
  
          imgCrpLab = imgCrp.Convert&lt;Lab, Byte&gt;();
          imgIsolatedCathNTipBW = new Image&lt;Gray, Byte&gt;(imgCrp.Size);
          CvInvoke.cvInRangeS(imgCrpLab.Split()[2], new MCvScalar(0), new MCvScalar(100), imgIsolatedCathNTipBW);
  
          imgCrpNoBgrnd = imgCrp.Copy(imgIsolatedCathNTipBW.Not());
          imgCrpNoBgrndGray = imgCrpNoBgrnd.Convert&lt;Gray, Byte&gt;().PyrUp().PyrDown();
          Thread.Sleep(1000);
          imgCrpNoBgrndGray.Save(DateTime.Now.ToString("yyMMddHHmmss") + ".jpg");
  
          Gray cannyThreshold = new Gray(150);
          Gray cannyThresholdLinking = new Gray(85);
          Gray circleAccumulatorThreshold = new Gray(15);
  
          imgCrpNoBgrndGrayCanny = imgCrpNoBgrndGray.Canny(cannyThreshold.Intensity, cannyThresholdLinking.Intensity);
          Thread.Sleep(1000);
          imgCrpNoBgrndGrayCanny.Save(DateTime.Now.ToString("yyMMddHHmmss") + ".jpg");
  
          circarrTip = imgCrpNoBgrndGrayCanny.HoughCircles(
              cannyThreshold,
              circleAccumulatorThreshold,
              1, //Resolution of the accumulator used to detect centers of the circles
              500, //min distance 
              15, //min radius
              42 //max radius
              )[0]; //Get the circles from the first channel
  
          imgCathNoTip = imgIsolatedCathNTipBW.Copy().Not();
          foreach (CircleF circle in circarrTip)
          {
              circLarger2RemTip = circle;
              circLarger2RemTip.Radius = circle.Radius;
              imgCathNoTip.Draw(circLarger2RemTip, new Gray(140), 1); // -1 IS TO FILL THE CIRCLE
          }
          Thread.Sleep(1000);
          imgCathNoTip.Save(DateTime.Now.ToString("yyMMddHHmmss") + ".jpg");
  </code></pre>
  
  <p>Sleep commands are just to make sure that the filenames will be different and will be removed later.
  I have also attached the images that have been save by this code during the process. The last image shows the detected circle which is larger and also shifted to the right.</p>
  
  <p>Can anyone kindly check my code and let me know how I can improve it to detect circles more accurately?</p>
  
  <p>Thanks in advance.</p>
  
  <p><img src="https://i.stack.imgur.com/Pm6SJ.jpg" alt="enter image description here">
  <img src="https://i.stack.imgur.com/4RTn5.jpg" alt="enter image description here">
  <img src="https://i.stack.imgur.com/Da9jf.jpg" alt="enter image description here">
  <img src="https://i.stack.imgur.com/dkAza.jpg" alt="enter image description here"></p>