0

我正在努力使用 OpenCV for C++ 进行形状检测。三角形和矩形等边缘图形的检测无故障。但是当涉及到圆时,它估计顶点数最多为 6-8 个。有人可以帮我吗?

void getContours(Mat video){
    Mat grayscale, canny_output;
    cvtColor(video, grayscale,COLOR_RGB2GRAY);//converting image to grayscale
    GaussianBlur(grayscale, grayscale, Size(9, 9), 2, 2 );
    threshold(grayscale, grayscale,60,255,THRESH_BINARY);
    vector <vector<Point>> contours, output_contour;
    vector <Vec4i> hierarchy;
    findContours( grayscale, contours, hierarchy, RETR_TREE,CHAIN_APPROX_SIMPLE );
    Mat drawing = Mat::zeros( grayscale.size(), CV_8UC3 );
    vector<Point> c; 
    for (size_t i = 0; i<contours.size(); i++){
        c = contours[i];
        Rect crect = boundingRect(c);
        // compute the center of the contour, then detect the name of the
        // shape using only the contour
        Moments M = moments(c);
        int cX, cY;
        cX = static_cast<int>(M.m10/M.m00);
        cY = static_cast<int>(M.m01/M.m00);
        string shape = detect(Mat(c));
        drawContours( drawing, contours, (int)i, Scalar(0, 255, 0), 2);
        Point pt(cX,cY);
        putText(drawing,shape,pt, FONT_HERSHEY_SIMPLEX, 0.5, Scalar(255, 255, 255), 2);
        imshow("contour", drawing);
        
    }
}
string detect(const Mat &curve){
    string shape = "unidentified";
    double peri = arcLength(curve, true);
    Mat approx;
    approxPolyDP(curve, approx, 0.04 * peri, true); // 0.01~0.05
    const int num_of_vertices = approx.rows;
    if(num_of_vertices == 0){
        shape = "circle";
        
    }
    if(num_of_vertices==2){
        shape = "line"; 
    }
    cout<<"\n"<<num_of_vertices;
    return to_string(num_of_vertices);

}

错误检测的例子。 4 是窗口本身的顶点

4

0 回答 0