无法在 OpenCV 中执行近似的 PolyDp 函数

Can't execute approxPolyDp function in OpenCV

本文关键字:PolyDp 函数 执行 OpenCV      更新时间:2023-10-16

我正在尝试将轮廓转换为多边形曲线集,但是当我尝试使用近似PolyDP函数时,我卡住了。首先,我测试了findContours是否正常工作,并尝试在我的图像中绘制轮廓 - 它适用于contourIdx = 0。然后我尝试使用近似PolyDp,如示例所示: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;

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

OpenCV-doc 说approxPolyDP

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

近似曲线 - ...类型应与输入曲线的类型匹配。...

因此,实现的最后一部分应该是:

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

我用这个小的更改测试你的代码,它编译并输出了共鸣的结果。

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

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

vector<vector<Point>> contoursOUT;

使用这个是正确的,

vector<Point> contoursOUT;

此外,在多个对象的情况下使用 for 循环。