Convexity defects C++ OpenCv

前端 未结 2 642
小蘑菇
小蘑菇 2020-12-01 10:07

I would be grateful to you if you could help me with this issue :)

Relating to this question cvConvexityDefects in OpenCV 2.X / C++?, I have the same problem. The Op

2条回答
  •  无人及你
    2020-12-01 10:38

    found some direct approach using the cpp convexityDefects. Typehandling by convexHull-function. It fills by type, int* returns indizes, Point* returns coordinates.

    void WorkFrame( Mat img, double minArea )
    {
    //assumption:
    // img already preprocessed, threshold, gray, smooth, morphology whatever..
    
    //get some contours
    vector > contours;
    vector hierarchy;
    findContours( img, contours, hierarchy, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE );
    
    for( int i=0; i& c=contours[i];
        double area = contourArea( c );
            if( area ptHull1; //uncomment and compare to ptHull2
        //convexHull( c, ptHull1 ); //convexHull is smart and fills direct coordinates
    
        std::vector ihull; 
        convexHull( c, ihull ); //convexHull is smart and fills in contourIndices
    
        std::vector defects;
        convexityDefects( c, ihull, defects ); //expects indexed hull (internal assertion mat.channels()==1)
    
        std::vector< Point > ptHull2;
        std::vector::iterator ii=ihull.begin();
        while( ii!=ihull.end() )
        {
            int idx=(*ii);
            ptHull2.push_back( c[idx] );
            ii++;
        }
        cv::polylines( mat, c, true, Scalar( 0xCC,0xCC,0xCC ), 1 );
        cv::polylines( mat, ptHull2, true, Scalar( 0xFF, 0x20, 0x20 ), 1 );
    
        std::vector::iterator d=defects.begin();
        while( d!=defects.end() )
        {
            Vec4i& v=(*d); d++;
            int startidx=v[0]; Point ptStart( c[startidx] );
            int endidx=v[1]; Point ptEnd( c[endidx] );
            int faridx=v[2]; Point ptFar( c[faridx] );
    
            cv::circle( img, ptStart, 4, Scalar( 0x02,0x60,0xFF ), 2 );
            cv::circle( img, ptEnd,   4, Scalar( 0xFF,0x60,0x02 ), 2 );
            cv::circle( img, ptFar,   4, Scalar( 0x60,0xFF,0x02 ), 2 );
        }
    }
    

    }

提交回复
热议问题