Обнаружение окружности с помощью Emgu и Kinect

#c# #geometry #shape #emgucv

#c# #геометрия #формы #emgucv

Вопрос:

Я начал программировать на C # недавно, для учебы. Прямо сейчас я погружаюсь в мир Kinect, и я абсолютно ошеломлен всеми возможностями.

В настоящее время я пытаюсь разработать программу, которая способна обнаруживать простые формы. Пока моя программа работает и обнаруживает основные формы, такие как треугольники или прямоугольники.

Но теперь я наткнулся на проблему с обнаружением кругов. Код из учебника, как показано здесь, не работает для моего решения.

 Stopwatch watch = Stopwatch.StartNew();
double cannyThreshold = 180.0;
double circleAccumulatorThreshold = 120;

CircleF[] circles = gray.HoughCircles(
    new Gray(cannyThreshold),
    new Gray(circleAccumulatorThreshold),
    2.0,  // Resolution of the accumulator used to detect centers of the circles
    20.0, // min distance 
    5,    // min radius
    0     // max radius
    )[0]; // Get the circles from the first channel

watch.Stop();
msgBuilder.Append(String.Format("Hough circles - {0} ms; ", watch.ElapsedMilliseconds));
  

Я не могу найти причину, я не получаю сообщение об ошибке, и отладка мне не помогает (имейте в виду, что я новичок). Я использую вспомогательный класс, чтобы убедиться, что EMGU отлично работает с WPF-Image-Toolbox и, как уже упоминалось: треугольники и прямоугольники работают.

Для моего кода: я пытаюсь обнаруживать фигуры в определенной области глубины. Для я смотрю на «срез» диапазона глубины и применяю следующий код:

 if(depthFrame != null)
{   
    depthSlice = depthFrame.SliceDepthImage(minVal, maxVal);
    Image<Bgr, Byte> sliced_img = new Image<Bgr, byte>(depthSlice.ToBitmap());
    Image<Gray, byte> buffer_img = sliced_img.Convert<Gray, byte>();

    List<Triangle2DF> triangleList = new List<Triangle2DF>();
    List<MCvBox2D> boxList = new List<MCvBox2D>();

    double cannyThreshold = 180.0;
    double circleAccumulatorThreshold = 120;

    CircleF[] circles = buffer_img.HoughCircles(
      new Gray(cannyThreshold),
      new Gray(circleAccumulatorThreshold),
      2.0,  // Resolution of the accumulator used to detect centers of the circles
      20.0, // min distance 
      5,    // min radius
      0     // max radius
      )[0]; // Get the circles from the first channel

    using(MemStorage storage = new MemStorage())
    {
        Contour<System.Drawing.Point> blobContours = buffer_img.FindContours(CHAIN_APPROX_METHOD.CV_CHAIN_APPROX_SIMPLE, RETR_TYPE.CV_RETR_EXTERNAL, storage);

        for(int i = 0; blobContours != null; blobContours = blobContours.HNext)
        {
           Contour<System.Drawing.Point> currentContours = blobContours.ApproxPoly(blobContours.Perimeter * 0.05, storage);

           if(currentContours.Area > 200)
           {
              if (currentContours.Total == 3)
              {
                 System.Drawing.Point[] pts = currentContours.ToArray();
                 triangleList.Add(new Triangle2DF(pts[0], pts[1], pts[2]));
              }
              else if(currentContours.Total == 4)
              {
                 bool isRect = true;
                 System.Drawing.Point[] pts = currentContours.ToArray();
                 LineSegment2D[] edges = Emgu.CV.PointCollection.PolyLine(pts, true);

                 for (int a = 0; a < edges.Length; a  )
                 {
                     double angle = Math.Abs(
                     edges[(a   1) % edges.Length].GetExteriorAngleDegree(edges[a]));

                     if (angle < 80 || angle > 100)
                     {
                        isRect = false;
                        break;
                     }
                  }

                  if (isRect) 
                     boxList.Add(currentContours.GetMinAreaRect());
               }
            }

             /*  if(blobContours.Area > 4000) // Generic Blob Detection
              *  {
              *      MCvBox2D contour_rectangle = blobContours.GetMinAreaRect();
              *      sliced_img.Draw(contour_rectangle, new Bgr(0, 255, 0), 4);
              *      blobCount  ;
              *  }
              */
     }
}

foreach(Triangle2DF triangle in triangleList)
{
   sliced_img.Draw(triangle, new Bgr(0, 0, 255), 4);
}

foreach (MCvBox2D box in boxList)
{
   sliced_img.Draw(box, new Bgr(0, 255, 0), 4);
}

foreach (CircleF circle in circles)
{
   sliced_img.Draw(circle, new Bgr(255, 0, 0), 8);
   Console.WriteLine(circle.Center);
}

outImg2.Source = ImageHelpers.ToBitmapSource(sliced_img);
  

Я делаю что-то не так? Или я что-то упускаю?
Приветствую и заранее благодарю 🙂

Комментарии:

1. Можете ли вы загрузить и поделиться изображением, над которым вы работаете, и желаемым результатом?

2. Я мог бы загрузить его, когда вам это понадобится для решения аналогичной проблемы. Если это ради помощи: мне удалось решить мою проблему 🙂