axel axel - 3 months ago 78
C++ Question

Delaunay triangulation opencv c++

I made a delaunay triangulation with openCv thanks to this code :
example code
(in partiluclar draw_subdiv).
However, when I want to display the triangulation, I get the mesh and lines who don't belong to triangulation.This lines are due to the fact that the triangulation algorithm starts its job considering triangles posted at "infinity".

Can you explain me how to draw only the mesh into the convex hull please (without this lines) ?

display function :

void draw_subdiv(Mat &img, Subdiv2D& subdiv, Scalar delaunay_color)
{

vector<Vec6f> triangleList;
subdiv.getTriangleList(triangleList);
vector<Point> pt(3);

for(size_t i = 0; i < triangleList.size(); ++i)
{
Vec6f t = triangleList[i];

pt[0] = Point(cvRound(t[0]), cvRound(t[1]));
pt[1] = Point(cvRound(t[2]), cvRound(t[3]));
pt[2] = Point(cvRound(t[4]), cvRound(t[5]));

line(img, pt[0], pt[1], delaunay_color, 1);
line(img, pt[1], pt[2], delaunay_color, 1);
line(img, pt[2], pt[0], delaunay_color, 1);
}
}


main function :

Mat image = imread(argv[1], 1);

..... ....
//creat delaunay
Scalar delaunay_color(255, 255, 255), point_color(0,0,255);
Rect rect(0,0,image.cols, image.rows);

Subdiv2D subdiv(rect);

for(int i = 0; i < point.getDim(); ++i)
{
Point2f fp(point.getCoord()[i].real(), point.getCoord()[i].imag());
subdiv.insert(fp);
}

draw_subdiv(image, subdiv, delaunay_color);
imwrite("data/delaunay.jpg", image);


Result:

enter image description here

Answer

Well I think it is easy. Just detect when the points are out of the image and dont draw them.

In your display function write:

 void draw_subdiv(Mat &img, Subdiv2D& subdiv, Scalar delaunay_color)
{
  bool draw;
  vector<Vec6f> triangleList;
  subdiv.getTriangleList(triangleList);
  vector<Point> pt(3);

  for(size_t i = 0; i < triangleList.size(); ++i)
    {
      Vec6f t = triangleList[i];

      pt[0] = Point(cvRound(t[0]), cvRound(t[1]));
      pt[1] = Point(cvRound(t[2]), cvRound(t[3]));
      pt[2] = Point(cvRound(t[4]), cvRound(t[5]));
      // MY PIECE OF CODE
      draw=true;

      for(int i=0;i<3;i++){
         if(pt[i].x>img.width||pt[i].y>img.heigth||pt[i].x<0||pt[i].y<0)
            draw=false;
      }
      if (draw){
         line(img, pt[0], pt[1], delaunay_color, 1);
         line(img, pt[1], pt[2], delaunay_color, 1);
         line(img, pt[2], pt[0], delaunay_color, 1);
      }


    }
}
Comments