Shape Detection in python using OpenCV

后端 未结 1 901
遥遥无期
遥遥无期 2020-12-04 20:44

I\'m working on a project in which I use OpenCV to detect shapes and their colors.

There are 5 colors (red, green, yellow, blue and white) and 4 shapes (rectangle, s

相关标签:
1条回答
  • 2020-12-04 21:05

    Here is the code I proceed with your image, the code will do

    1. Blur the source
    2. Canny Edge detection.
    3. Find contour.
    4. approxPolyDP for the contour.
    5. Check total size of approxPolyDP points.

    Code:

       Mat src=imread("src.jpg",1);
       Mat thr,gray;
       blur(src,src,Size(3,3));
       cvtColor(src,gray,CV_BGR2GRAY);
       Canny(gray,thr,50, 190, 3, false );
       vector<vector<Point> > contours;
       vector<Vec4i> hierarchy;
       findContours( thr.clone(),contours,hierarchy,CV_RETR_EXTERNAL,CV_CHAIN_APPROX_SIMPLE,Point(0,0));
    
       vector<vector<Point> > contours_poly(contours.size());
       vector<Rect> boundRect( contours.size() );
       vector<Point2f>center( contours.size() );
       vector<float>radius( contours.size() );
       vector<vector<Point> >hull( contours.size() );
       for( int i = 0; i < contours.size(); i++ )
        {
        approxPolyDP( Mat(contours[i]), contours_poly[i], 10, true );
        boundRect[i] = boundingRect( Mat(contours_poly[i]) );
        minEnclosingCircle( (Mat)contours_poly[i], center[i], radius[i] );
        convexHull( Mat(contours[i]), hull[i], false );
    
        if( contours_poly[i].size()>15) // Check for corner
           drawContours( src, contours_poly, i, Scalar(0,255,0), 2, 8, vector<Vec4i>(), 0, Point() ); // True object
        else
           drawContours( src, contours_poly, i, Scalar(0,0,255), 2, 8, vector<Vec4i>(), 0, Point() ); // false object
          //drawContours( src, hull, i, Scalar(0,0,255), 2, 8, vector<Vec4i>(), 0, Point() );
          // rectangle( src, boundRect[i].tl(), boundRect[i].br(), Scalar(0,255,0), 2, 8, 0 );
           //circle( src, center[i], (int)radius[i], Scalar(0,0,255), 2, 8, 0 );
        }
       imshow("src",src);
       imshow("Canny",thr);
       waitKey();
    

    enter image description here enter image description here

    0 讨论(0)
提交回复
热议问题