首页 文章

OpenCV C / Obj-C:检测一张纸/方形检测

提问于
浏览
158

我在我的测试应用程序中成功实现了OpenCV平方检测示例,但现在需要过滤输出,因为它非常混乱 - 或者我的代码是错误的?

我对本文的四个角点感兴趣(如that)和进一步处理......

Input & Output:
Input & Output

Original image:

click

Code:

double angle( cv::Point pt1, cv::Point pt2, cv::Point pt0 ) {
    double dx1 = pt1.x - pt0.x;
    double dy1 = pt1.y - pt0.y;
    double dx2 = pt2.x - pt0.x;
    double dy2 = pt2.y - pt0.y;
    return (dx1*dx2 + dy1*dy2)/sqrt((dx1*dx1 + dy1*dy1)*(dx2*dx2 + dy2*dy2) + 1e-10);
}

- (std::vector<std::vector<cv::Point> >)findSquaresInImage:(cv::Mat)_image
{
    std::vector<std::vector<cv::Point> > squares;
    cv::Mat pyr, timg, gray0(_image.size(), CV_8U), gray;
    int thresh = 50, N = 11;
    cv::pyrDown(_image, pyr, cv::Size(_image.cols/2, _image.rows/2));
    cv::pyrUp(pyr, timg, _image.size());
    std::vector<std::vector<cv::Point> > contours;
    for( int c = 0; c < 3; c++ ) {
        int ch[] = {c, 0};
        mixChannels(&timg, 1, &gray0, 1, ch, 1);
        for( int l = 0; l < N; l++ ) {
            if( l == 0 ) {
                cv::Canny(gray0, gray, 0, thresh, 5);
                cv::dilate(gray, gray, cv::Mat(), cv::Point(-1,-1));
            }
            else {
                gray = gray0 >= (l+1)*255/N;
            }
            cv::findContours(gray, contours, CV_RETR_LIST, CV_CHAIN_APPROX_SIMPLE);
            std::vector<cv::Point> approx;
            for( size_t i = 0; i < contours.size(); i++ )
            {
                cv::approxPolyDP(cv::Mat(contours[i]), approx, arcLength(cv::Mat(contours[i]), true)*0.02, true);
                if( approx.size() == 4 && fabs(contourArea(cv::Mat(approx))) > 1000 && cv::isContourConvex(cv::Mat(approx))) {
                    double maxCosine = 0;

                    for( int j = 2; j < 5; j++ )
                    {
                        double cosine = fabs(angle(approx[j%4], approx[j-2], approx[j-1]));
                        maxCosine = MAX(maxCosine, cosine);
                    }

                    if( maxCosine < 0.3 ) {
                        squares.push_back(approx);
                    }
                }
            }
        }
    }
    return squares;
}

EDIT 17/08/2012:

要在图像上绘制检测到的方块,请使用以下代码:

cv::Mat debugSquares( std::vector<std::vector<cv::Point> > squares, cv::Mat image )
{
    for ( int i = 0; i< squares.size(); i++ ) {
        // draw contour
        cv::drawContours(image, squares, i, cv::Scalar(255,0,0), 1, 8, std::vector<cv::Vec4i>(), 0, cv::Point());

        // draw bounding rect
        cv::Rect rect = boundingRect(cv::Mat(squares[i]));
        cv::rectangle(image, rect.tl(), rect.br(), cv::Scalar(0,255,0), 2, 8, 0);

        // draw rotated rect
        cv::RotatedRect minRect = minAreaRect(cv::Mat(squares[i]));
        cv::Point2f rect_points[4];
        minRect.points( rect_points );
        for ( int j = 0; j < 4; j++ ) {
            cv::line( image, rect_points[j], rect_points[(j+1)%4], cv::Scalar(0,0,255), 1, 8 ); // blue
        }
    }

    return image;
}

5 回答

  • 2

    你需要的是一个 quadrangle 而不是一个旋转的矩形 . RotatedRect 会给你不正确的结果 . 您还需要透视投影 .

    基本上必须做的是:

    • 遍历所有多边形线段并连接几乎相等的线段 .

    • 对它们进行排序,以便拥有4个最大的线段 .

    • 与这些线相交,你有4个最可能的角点 .

    • 在从角点和已知对象的纵横比收集的透视图上转换矩阵 .

    我实现了一个类 Quadrangle ,它负责轮廓到四边形转换,并且还将在正确的视角上对其进行转换 .

    请参阅此处的工作实施:Java OpenCV deskewing a contour

  • 147

    好吧,我迟到了 .


    在您的图像中,纸张是 white ,而背景是 colored . 因此,最好在 HSV color space 中检测到纸张是 Saturation(饱和度) 通道 . 首先参考wiki HSL_and_HSV . 然后我会在这个Detect Colored Segment in an image中从我的回答中复制出大部分想法 .


    主要步骤:

    • 阅读 BGR

    • 将图像从 bgr 转换为 hsv 空间

    • 阈值S通道

    • 然后找到最大外部轮廓(或根据需要选择 CannyHoughLines ,我选择 findContours ),大约可以获得角点 .


    这是我的结果:

    enter image description here


    Python代码(Python 3.5 OpenCV 3.3):

    #!/usr/bin/python3
    # 2017.12.20 10:47:28 CST
    # 2017.12.20 11:29:30 CST
    
    import cv2
    import numpy as np
    
    ##(1) read into  bgr-space
    img = cv2.imread("test2.jpg")
    
    ##(2) convert to hsv-space, then split the channels
    hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
    h,s,v = cv2.split(hsv)
    
    ##(3) threshold the S channel using adaptive method(`THRESH_OTSU`) or fixed thresh
    th, threshed = cv2.threshold(s, 50, 255, cv2.THRESH_BINARY_INV)
    
    ##(4) find all the external contours on the threshed S
    #_, cnts, _ = cv2.findContours(threshed, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    cnts = cv2.findContours(threshed, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[-2]
    
    canvas  = img.copy()
    #cv2.drawContours(canvas, cnts, -1, (0,255,0), 1)
    
    ## sort and choose the largest contour
    cnts = sorted(cnts, key = cv2.contourArea)
    cnt = cnts[-1]
    
    ## approx the contour, so the get the corner points
    arclen = cv2.arcLength(cnt, True)
    approx = cv2.approxPolyDP(cnt, 0.02* arclen, True)
    cv2.drawContours(canvas, [cnt], -1, (255,0,0), 1, cv2.LINE_AA)
    cv2.drawContours(canvas, [approx], -1, (0, 0, 255), 1, cv2.LINE_AA)
    
    ## Ok, you can see the result as tag(6)
    cv2.imwrite("detected.png", canvas)
    

    相关答案:

  • 38

    检测纸张是有点老派 . 如果你想解决偏斜检测问题,那么最好是直接针对文本行检测 . 通过这个,您将获得左,右,上,下的极值 . 如果您不想要,请丢弃图像中的任何图形,然后对文本线段进行一些统计,以找到最常出现的角度范围或更确切的角度 . 这就是你将如何缩小到一个良好的倾斜角度 . 在此之后,您将这些参数设置为倾斜角度和极值以进行校正并将图像切割为所需的图像 .

    至于当前的图像要求,最好是尝试CV_RETR_EXTERNAL而不是CV_RETR_LIST .

    另一种检测边缘的方法是在纸边缘上训练随机森林分类器,然后使用分类器获取边缘Map . 这是迄今为止强有力的方法,但需要培训和时间 .

    随机森林将使用低对比度差异情景,例如大致白色背景上的白皮书 .

  • -1

    除非没有指定其他要求,否则我只是将您的彩色图像转换为灰度并仅使用它(不需要在3个通道上工作,对比度已经过高) . 此外,除非有关于调整大小的某些特定问题,否则我会使用缩小版本的图像,因为它们相对较大并且大小不会对正在解决的问题增加任何内容 . 然后,最后,您的问题通过中值滤波器,一些基本的形态学工具和统计数据来解决(主要用于Otsu阈值处理,已经为您完成) .

    这是我用你的样本图像获得的,以及我在周围找到的一张纸上的其他图像:

    enter image description here

    enter image description here

    中值滤波器用于从现在的灰度图像中删除细微的细节 . 它可能会去除发白纸内的细线,这很好,因为这样你就会以微小的连接组件结束,这些组件很容易丢弃 . 在中位数之后,应用形态梯度(简单地 dilation - erosion )并将结果二进制化为Otsu . 形态梯度是保持强边缘的好方法,应该多用 . 然后,由于此渐变将增加轮廓宽度,因此应用形态细化 . 现在您可以丢弃小组件 .

    在这一点上,这是我们对上面的右图(在绘制蓝色多边形之前)所具有的,左边的一个没有显示,因为唯一剩下的组件是描述纸张的组件:

    enter image description here

    给出这些示例,现在唯一的问题是区分看起来像矩形的组件和其他没有的组件 . 这是确定包含该形状的凸包的面积与其边界框的面积之间的比率的问题 . 比率0.7适用于这些例子 . 可能的情况是,您还需要丢弃纸张内部的组件,但不是在这些示例中使用此方法(尽管如此,执行此步骤应该非常特别容易,因为它可以通过OpenCV直接完成) .

    作为参考,这是Mathematica中的示例代码:

    f = Import["http://thwartedglamour.files.wordpress.com/2010/06/my-coffee-table-1-sa.jpg"]
    f = ImageResize[f, ImageDimensions[f][[1]]/4]
    g = MedianFilter[ColorConvert[f, "Grayscale"], 2]
    h = DeleteSmallComponents[Thinning[
         Binarize[ImageSubtract[Dilation[g, 1], Erosion[g, 1]]]]]
    convexvert = ComponentMeasurements[SelectComponents[
         h, {"ConvexArea", "BoundingBoxArea"}, #1 / #2 > 0.7 &], 
         "ConvexVertices"][[All, 2]]
    (* To visualize the blue polygons above: *)
    Show[f, Graphics[{EdgeForm[{Blue, Thick}], RGBColor[0, 0, 1, 0.5], 
         Polygon @@ convexvert}]]
    

    如果有更多不同的情况,纸张的矩形没有很好地定义,或者方法将其与其他形状混淆 - 这些情况可能由于各种原因而发生,但一个常见原因是图像采集不良 - 然后尝试结合前 - 使用“基于窗口Hough变换的矩形检测”一文中描述的工作处理步骤 .

  • 9

    这是Stackoverflow中反复出现的主题,由于我无法找到相关的实现,我决定接受挑战 .

    我对OpenCV中的正方形演示进行了一些修改,下面得到的C代码能够检测到图像中的一张纸:

    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
                        if (approx.size() == 4 &&
                                fabs(contourArea(Mat(approx))) > 1000 &&
                                isContourConvex(Mat(approx)))
                        {
                                double maxCosine = 0;
    
                                for (int j = 2; j < 5; j++)
                                {
                                        double cosine = fabs(angle(approx[j%4], approx[j-2], approx[j-1]));
                                        maxCosine = MAX(maxCosine, cosine);
                                }
    
                                if (maxCosine < 0.3)
                                        squares.push_back(approx);
                        }
                }
            }
        }
    }
    

    执行此程序后,纸张将成为 vector<vector<Point> > 中的最大正方形:

    opencv paper sheet detection

    我让你写功能找到最大的方块 . ;)

相关问题