How can I detect registration markers on paper using OpenCV?

前端 未结 1 1957
时光取名叫无心
时光取名叫无心 2021-01-02 19:38

I\'ve been trying to find the best way to detect the 4 black squares on the paper and use them to isolate the paper in its own image.

相关标签:
1条回答
  • 2021-01-02 20:16

    It seems that on your image there are only 4 black squares so what you have to do is:

    1. Convert image to grays
    2. Do threshold
    3. Find black contours (before doing this in OpenCV you have to invert your image, because by default OpenCV finds white contours)
    4. Cycle through these contours and find bounding rectangle.
    5. Do the check:

      A) Rectangle's area is bigger that some constant (in my solution it was 100)

      B) Rectangle's width/height is near 1.0 (in my soultion it was [0.9, 1.1] range)

    The code:

    Mat img = imread("test.jpg"), gray;
    vector<Vec4i> hierarchy;
    vector<vector<Point2i> > contours;
    cvtColor(img, gray, CV_BGR2GRAY);
    threshold(gray, gray, 100, 255, THRESH_BINARY);
    bitwise_not(gray, gray);
    
    findContours(gray, contours, hierarchy, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE);
    
    for(size_t i=0; i<contours.size(); i++)
    {
        Rect rect = boundingRect(contours[i]);
        double k = (rect.height+0.0)/rect.width;
        if (0.9<k && k<1.1 && rect.area()>100)
        {
            drawContours(img, contours, i, Scalar(0,0,255));
        }
    }
    
    imshow("result", img);
    waitKey();
    

    Result: enter image description here

    Also read this SO discussion - you don't need that 4 squares to detect paper.

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