Opencv: false number of vertices of a circle

85 Views Asked by At

Im struggling with the shape detection using OpenCV for C++. The edged figures such as triangle and rectangular are detected trouble-free. But when it comes to circle it estimates number of vertices up to 6-8. Could somebody help me?

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);

}

example of false detection. The 4 is the vertices of the window itself

0

There are 0 best solutions below