无法在OpenCV中执行approxPolyDp函数

时间:2013-10-24 10:07:35

标签: c++ opencv

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

但是在执行过程中我遇到了与矢量类和函数size()相关的错误“Acces violation”。这是我的代码:

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;

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

2 个答案:

答案 0 :(得分: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 );

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

答案 1 :(得分:1)

我建议你先在opencv中正确学习aboutPolyDP的文档。

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

vector<vector<Point>> contoursOUT;

使用正确的

vector<Point> contoursOUT;

此外,如果有多个对象用于循环。