0

我正在尝试将轮廓转换为一组多边形曲线,但是当我尝试使用 approxPolyDP 函数时我被卡住了。首先我测试了 findContours 是否正常工作并尝试在我的图像中绘制轮廓 - 它适用于 contourIdx = 0。然后我尝试使用 approxPolyDp,如示例所示:http ://docs.opencv.org/doc/tutorials/imgproc/ shapedescriptors/bounding_rects_circles/bounding_rects_circles.html

但是在执行过程中,我遇到了与向量类和函数大小()相关的错误“访问冲突”。这是我的代码:

IplImage* image = cvLoadImage("F:\\triangle.png");
waitKey(5000);
//Mat img = imread("triangle.png");
Mat img(image,true);

if(!img.data)
{
    cout <<"image file not found";
      cv::waitKey(5000);
   return -1;
}

//namedWindow( "window", 0 );
//imshow( "window", img );
cvNamedWindow("window");
cvShowImage("window",image);

Mat imgGray;
Mat imgEdges;

cvtColor(img,imgGray,CV_BGR2GRAY);
blur(imgGray,imgGray,Size(3,3));
threshold(imgGray,imgEdges,128,255,CV_THRESH_BINARY);

Mat canny_output;
vector<vector<Point>> contours;
vector<Vec4i> hierarchy;

/// Detect edges using canny
Canny( imgGray, canny_output,100, 100*2, 3 );
/// Find contours
findContours( canny_output, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, Point(0, 0) );

 /// Draw contours
 RNG rng(12345);
 Mat drawing = Mat::zeros( canny_output.size(), CV_8UC3 );

 if (drawing.type() != CV_8UC3)
 {
  cout << "Error: image type different then CV_8UC3";
 }

   Scalar color = Scalar( rng.uniform(0, 255), rng.uniform(0,255), rng.uniform(0,255) );
   drawContours( drawing, contours, 0, color, 2, 8, hierarchy, 0, Point() );


 IplImage img3 = drawing;
 cvNamedWindow( "Contours", CV_WINDOW_AUTOSIZE );
 cvShowImage( "Contours", &img3 );

 vector<vector<Point>> contoursOUT/*(contours.size())*/;

 approxPolyDP(Mat(contours[0]),contoursOUT,3,true );


waitKey(0);
return 0;

有谁知道这里有什么问题?

4

2 回答 2

4

OpenCV-doc 说approxPolyDP

void approxPolyDP (InputArray curve, 
                   OutputArray approxCurve, 
                   double epsilon, 
                   bool closed) 

approxCurve - ... 类型应与输入曲线的类型相匹配。...

所以你实现的最后一部分应该是:

vector<Point> contoursOUT;
approxPolyDP( Mat(contours[0]), contoursOUT, 3, true );

我用这个小改动测试了你的代码,它编译并输出了合理的结果。

于 2014-01-10T13:43:38.430 回答
0

我建议您首先正确研究 opencv 中 approxPolyDP 的文档。

现在谈论你的代码,你做了一个错误的声明。

vector<vector<Point>> contoursOUT;

使用这个是正确的,

vector<Point> contoursOUT;

此外,如果有多个对象,请使用 for 循环。

于 2018-01-29T10:56:12.993 回答