OpenCV C ++ / Obj-C:高级正方形检测

不久前,我问了一个关于平方检测的问题,卡尔菲利普得出了不错的结果。


现在,我想更进一步,找到边缘不完全可见的正方形。看一下这个例子:



有任何想法吗?我正在使用karlphillips代码:


void find_squares(Mat& image, vector<vector<Point> >& squares)

{

    // blur will enhance edge detection

    Mat blurred(image);

    medianBlur(image, blurred, 9);


    Mat gray0(blurred.size(), CV_8U), gray;

    vector<vector<Point> > contours;


    // find squares in every color plane of the image

    for (int c = 0; c < 3; c++)

    {

        int ch[] = {c, 0};

        mixChannels(&blurred, 1, &gray0, 1, ch, 1);


        // try several threshold levels

        const int threshold_level = 2;

        for (int l = 0; l < threshold_level; l++)

        {

            // Use Canny instead of zero threshold level!

            // Canny helps to catch squares with gradient shading

            if (l == 0)

            {

                Canny(gray0, gray, 10, 20, 3); // 


                // Dilate helps to remove potential holes between edge segments

                dilate(gray, gray, Mat(), Point(-1,-1));

            }

            else

            {

                    gray = gray0 >= (l+1) * 255 / threshold_level;

            }


            // Find contours and store them in a list

            findContours(gray, contours, CV_RETR_LIST, CV_CHAIN_APPROX_SIMPLE);


            // Test contours

            vector<Point> approx;

            for (size_t i = 0; i < contours.size(); i++)

            {

                    // approximate contour with accuracy proportional

                    // to the contour perimeter

                    approxPolyDP(Mat(contours[i]), approx, arcLength(Mat(contours[i]), true)*0.02, true);


                    // Note: absolute value of an area is used because

                    // area may be positive or negative - in accordance with the

                    // contour orientation


                    }

            }

        }

    }

}


德玛西亚99
浏览 650回答 3
3回答

青春有我

我尝试使用convex hull method它非常简单。在这里,您可以找到检测到的轮廓的凸包。它消除了纸张底部的凸度缺陷。下面是代码(在OpenCV-Python中):import cv2import numpy as npimg = cv2.imread('sof.jpg')img = cv2.resize(img,(500,500))gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)ret,thresh = cv2.threshold(gray,127,255,0)contours,hier = cv2.findContours(thresh,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)for cnt in contours:&nbsp; &nbsp; if cv2.contourArea(cnt)>5000:&nbsp; # remove small areas like noise etc&nbsp; &nbsp; &nbsp; &nbsp; hull = cv2.convexHull(cnt)&nbsp; &nbsp; # find the convex hull of contour&nbsp; &nbsp; &nbsp; &nbsp; hull = cv2.approxPolyDP(hull,0.1*cv2.arcLength(hull,True),True)&nbsp; &nbsp; &nbsp; &nbsp; if len(hull)==4:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; cv2.drawContours(img,[hull],0,(0,255,0),2)cv2.imshow('img',img)cv2.waitKey(0)cv2.destroyAllWindows()(在这里,我并没有在所有平面上都找到正方形。如果需要,可以自己做。)
打开App,查看更多内容
随时随地看视频慕课网APP