我正在尝试编写一个代码,在其中我可以检测除正方形之外的不同几何形状,我发现:this answer here答案是用 python 给出的,我尝试用 c++ 编写,但我的程序崩溃了,知道我做错了什么:
int main (){
cv::Mat img = cv::imread("src.jpg",0);
cv::Mat image ;
std::vector<std::vector<cv::Point>> contours;
//std::vector<std::vector<cv::Point2f>> hiararchy;
cv::threshold(img,img,127,255,CV_THRESH_BINARY_INV);
cv::findContours(img,contours,/*hiararchy,*/CV_RETR_EXTERNAL,CV_RETR_CCOMP );
std::vector<cv::Point2f> approx;
for ( int i=0; i<contours.size();i++){
cv::approxPolyDP(cv::Mat(contours[i]),approx,cv::arcLength(cv::Mat(contours[i]),true)*0.02,true);
}
cv::waitKey(0);
return 0;
}
我已经调试了程序,它在cv::approxPolyDP函数中崩溃了!
**更新** 在 C. Canberk Bacı 的建议之后,我更改了 for l
for ( int i=0; i<contours.size();i++){
cv::Mat m(contours[i]);
cv::approxPolyDP(m,approx,cv::arcLength(m,true)*0.02,true);
}
但变化不大 预先感谢您的帮助!
最佳答案
明白了:
int main (){
cv::Mat img = cv::imread("src.jpg",0);
cv::Mat image ;
std::vector<std::vector<cv::Point>> contours;
//std::vector<std::vector<cv::Point2f>> hiararchy;
cv::threshold(img,img,127,255,CV_THRESH_BINARY_INV);
cv::findContours(img,contours,/*hiararchy,*/CV_RETR_EXTERNAL,CV_RETR_CCOMP );
std::vector<cv::Point> approx; // this should be 1D
for ( int i=0; i<contours.size();i++){
cv::approxPolyDP(cv::Mat(contours[i]),approx,(cv::arcLength(cv::Mat(contours[i]),true)*0.02),true);
}
cv::waitKey(0);
再次感谢您的帮助
关于c++ - 这个opencv代码有什么问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17716255/