OpenCV findContours 轮廓检索函数及轮廓特征计算

#include 
#include 
#include 
#include 

using namespace cv;
using namespace std;

void TraceEdge(int y, int x, int nThrLow, Mat &edgeDefualt, Mat &gradient);

int main()
{
double duration;
    Mat src = imread("stuff.bmp", 0);
    Mat srcColor = imread("stuff.bmp", 1);
    Mat srcResize, srcResizeThd, srcResizeColor;
    resize(srcColor, srcResizeColor, Size(srcColor.cols*0.5,srcColor.rows*0.5) );
    vector > contours;
    vector hierarchy;
duration = static_cast(getTickCount());

    resize(src, srcResize, Size(src.cols*0.5,src.rows*0.5) );
    adaptiveThreshold(srcResize, srcResizeThd, 255, ADAPTIVE_THRESH_GAUSSIAN_C, THRESH_BINARY, 21, 5);
    findContours(srcResizeThd, contours, hierarchy, RETR_LIST, CHAIN_APPROX_NONE);
    if( !contours.empty() && !hierarchy.empty() )
    {
        vector >::iterator it;
        for( it = contours.begin(); it != contours.end(); )
        {
//            //按轮廓面积筛选
//            if( contourArea(*it) < 2000 || contourArea(*it) > 10000 )
//                contours.erase(it);
//            else it ++;
//            //按轮廓长度筛选
//            if( arcLength(*it, true) < 230 || arcLength(*it, true) > 250 )
//                contours.erase(it);
//            else it ++;
            //-------最小外接矩形-------------------
            RotatedRect minRect = minAreaRect(*it);
            Point2f vertices[4];
            minRect.points(vertices);
            vector rectArea;//保存最小外接矩形的4个点
            for ( int n = 0; n < 4; n ++ )
            {
                Point temp;
                temp.x = vertices[n].x;
                temp.y = vertices[n].y;
                rectArea.push_back(temp);
            }
            //-------最小外接圆-------------------
            Point2f center;//圆心
            float radius;//半径
            minEnclosingCircle(*it, center, radius);
            if( contourArea(*it) < radius*radius*3.14*0.61
                || contourArea(*it) > radius*radius*3.14*0.75
                || contourArea(*it) < 2000 || contourArea(*it) > 10000
                || arcLength(*it, true) < 230 || arcLength(*it, true) > 250
              )
                contours.erase(it);
            else it ++;
        }
    }

duration = static_cast(getTickCount()) - duration;
duration /= getTickFrequency();
cout << duration << endl;
    drawContours(srcResizeColor, contours, -1, Scalar(0,0,255));
    namedWindow("src", 0);
    imshow("src", srcResizeColor);
    waitKey(0);
    return 0;
}

 

你可能感兴趣的:(Image,algorithm)