【opencv+C++】在图像中找四边形

本文介绍了一个使用 Opencv 和 C++ 实现的程序,该程序能从图像中找出四边形。通过滤波降噪、边缘检测、轮廓提取等步骤,并利用角度余弦值判断轮廓是否为四边形。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

【opencv+C++】在图像中找四边形

转载  2014年11月15日 14:02:40
[cpp]  view plain  copy
  1. /* 
  2. 这个程序的基本思想是:对输入的图像进行滤波去掉噪音,然后进行canny边缘检测,之后进行膨胀,然后寻找轮廓,对轮廓进行多边形的逼近,检测多边形的点数是否是4而且各个角的的余弦是否是小于某个值,程序中认为是0.3,然后就判断该多边形是四边形,之后根据这四个点画出该图像。 
  3.  
  4. ps:我对程序中余弦定理的使用 感觉公式用错了 
  5. */  
  6.   
  7. #include "stdafx.h"     
  8.     
  9. #include "cv.h"     
  10. #include "highgui.h"     
  11. #include <stdio.h>     
  12. #include <math.h>     
  13. #include <string.h>     
  14.     
  15.     
  16. int thresh = 50;     
  17. IplImage* img = 0;     
  18. IplImage* img0 = 0;     
  19. CvMemStorage* storage = 0;     
  20. CvPoint pt[4];     
  21. const char* wndname = "Square Detection Demo";     
  22.     
  23. // helper function:     
  24. // finds a cosine of angle between vectors     
  25. // from pt0->pt1 and from pt0->pt2      
  26. double angle( CvPoint* pt1, CvPoint* pt2, CvPoint* pt0 )     
  27. {     
  28.        double dx1 = pt1->x - pt0->x;     
  29.        double dy1 = pt1->y - pt0->y;     
  30.        double dx2 = pt2->x - pt0->x;     
  31.        double dy2 = pt2->y - pt0->y;     
  32.        //1e-10就是“aeb”的形式,表示a乘以10的b次方。     
  33.        //其中b必须是整数,a可以是小数。     
  34.        //?余弦定理CosB=(a^2+c^2-b^2)/2ac??所以这里的计算似乎有问题     
  35.        return (dx1*dx2 + dy1*dy2)/sqrt((dx1*dx1 + dy1*dy1)*(dx2*dx2 + dy2*dy2) + 1e-10);     
  36. }     
  37.     
  38. // returns sequence of squares detected on the image.     
  39. // the sequence is stored in the specified memory storage     
  40.     
  41. CvSeq* findSquares4( IplImage* img, CvMemStorage* storage )     
  42. {     
  43.        CvSeq* contours;     
  44.        int i, c, l, N = 11;     
  45.        CvSize sz = cvSize( img->width & -2, img->height & -2 );     
  46.        IplImage* timg = cvCloneImage( img ); // make a copy of input image     
  47.        IplImage* gray = cvCreateImage( sz, 8, 1 );      
  48.        IplImage* pyr = cvCreateImage( cvSize(sz.width/2, sz.height/2), 8, 3 );     
  49.        IplImage* tgray;     
  50.        CvSeq* result;     
  51.        double s, t;     
  52.        // create empty sequence that will contain points -     
  53.        // 4 points per square (the square's vertices)     
  54.        CvSeq* squares = cvCreateSeq( 0, sizeof(CvSeq), sizeof(CvPoint), storage );     
  55.          
  56.        // select the maximum ROI in the image     
  57.        // with the width and height divisible by 2     
  58.        cvSetImageROI( timg, cvRect( 0, 0, sz.width, sz.height ));     
  59.          
  60.        // down-scale and upscale the image to filter out the noise     
  61.        //使用gaussian金字塔分解对输入图像向下采样,首先对它输入的图像用指定滤波器     
  62.        //进行卷积,然后通过拒绝偶数的行与列来下采样     
  63.        cvPyrDown( timg, pyr, 7 );     
  64.        //函数 cvPyrUp 使用Gaussian 金字塔分解对输入图像向上采样。首先通过在图像中插入 0 偶数行和偶数列,然后对得到的图像用指定的滤波器进行高斯卷积,其中滤波器乘以4做插值。所以输出图像是输入图像的 4 倍大小。     
  65.        cvPyrUp( pyr, timg, 7 );     
  66.        tgray = cvCreateImage( sz, 8, 1 );     
  67.          
  68.        // find squares in every color plane of the image     
  69.        for( c = 0; c < 3; c++ )     
  70.        {     
  71.            // extract the c-th color plane     
  72.            //函数 cvSetImageCOI 基于给定的值设置感兴趣的通道。值 0 意味着所有的通道都被选定, 1 意味着第一个通道被选定等等。     
  73.            cvSetImageCOI( timg, c+1 );     
  74.            cvCopy( timg, tgray, 0 );     
  75.              
  76.            // try several threshold levels     
  77.            for( l = 0; l < N; l++ )     
  78.            {     
  79.                // hack: use Canny instead of zero threshold level.     
  80.                // Canny helps to catch squares with gradient shading        
  81.                if( l == 0 )     
  82.                {     
  83.                    // apply Canny. Take the upper threshold from slider     
  84.                    // and set the lower to 0 (which forces edges merging)      
  85.                    cvCanny( tgray, gray,60, 180, 3 );     
  86.                    // dilate canny output to remove potential     
  87.                    // holes between edge segments      
  88.                    //使用任意结构元素膨胀图像     
  89.                    cvDilate( gray, gray, 0, 1 );     
  90.                }     
  91.                else     
  92.                {     
  93.                    // apply threshold if l!=0:     
  94.                    //        tgray(x,y) = gray(x,y) < (l+1)*255/N ? 255 : 0     
  95.                    //cvThreshold( tgray, gray, (l+1)*255/N, 255, CV_THRESH_BINARY );     
  96.        cvThreshold( tgray, gray, 50, 255, CV_THRESH_BINARY );     
  97.                }     
  98.                  
  99.                // find contours and store them all as a list     
  100.                cvFindContours( gray, storage, &contours, sizeof(CvContour),     
  101.                    CV_RETR_LIST, CV_CHAIN_APPROX_SIMPLE, cvPoint(0,0) );     
  102.                  
  103.                // test each contour     
  104.                while( contours )     
  105.                {     
  106.                    // approximate contour with accuracy proportional     
  107.                    // to the contour perimeter     
  108.                    //用指定精度逼近多边形曲线     
  109.                    result = cvApproxPoly( contours, sizeof(CvContour), storage,     
  110.                        CV_POLY_APPROX_DP, cvContourPerimeter(contours)*0.02, 0 );     
  111.                    // square contours should have 4 vertices after approximation     
  112.                    // relatively large area (to filter out noisy contours)     
  113.                    // and be convex.     
  114.                    // Note: absolute value of an area is used because     
  115.                    // area may be positive or negative - in accordance with the     
  116.                    // contour orientation     
  117.                    //cvContourArea 计算整个轮廓或部分轮廓的面积     
  118.                    //cvCheckContourConvexity测试轮廓的凸性                       
  119.                    if( result->total == 4 &&     
  120.                        fabs(cvContourArea(result,CV_WHOLE_SEQ)) > 1000 &&     
  121.                        cvCheckContourConvexity(result) )     
  122.                    {     
  123.                        s = 0;     
  124.                          
  125.                        for( i = 0; i < 5; i++ )     
  126.                        {     
  127.                            // find minimum angle between joint     
  128.                            // edges (maximum of cosine)     
  129.                            if( i >= 2 )     
  130.                            {     
  131.                                t = fabs(angle(     
  132.                                (CvPoint*)cvGetSeqElem( result, i ),     
  133.                                (CvPoint*)cvGetSeqElem( result, i-2 ),     
  134.                                (CvPoint*)cvGetSeqElem( result, i-1 )));     
  135.                                s = s > t ? s : t;     
  136.                            }     
  137.                        }     
  138.                          
  139.                        // if cosines of all angles are small     
  140.                        // (all angles are ~90 degree) then write quandrange     
  141.                        // vertices to resultant sequence      
  142.                        if( s < 0.3 )     
  143.                            for( i = 0; i < 4; i++ )     
  144.                                cvSeqPush( squares,     
  145.                                    (CvPoint*)cvGetSeqElem( result, i ));     
  146.                    }     
  147.                      
  148.                    // take the next contour     
  149.                    contours = contours->h_next;     
  150.                }     
  151.            }     
  152.        }     
  153.          
  154.        // release all the temporary images     
  155.        cvReleaseImage( &gray );     
  156.        cvReleaseImage( &pyr );     
  157.        cvReleaseImage( &tgray );     
  158.        cvReleaseImage( &timg );     
  159.          
  160.        return squares;     
  161. }     
  162.     
  163.     
  164. // the function draws all the squares in the image     
  165. void drawSquares( IplImage* img, CvSeq* squares )     
  166. {     
  167.        CvSeqReader reader;     
  168.        IplImage* cpy = cvCloneImage( img );     
  169.        int i;     
  170.          
  171.        // initialize reader of the sequence     
  172.        cvStartReadSeq( squares, &reader, 0 );     
  173.          
  174.        // read 4 sequence elements at a time (all vertices of a square)     
  175.        for( i = 0; i < squares->total; i += 4 )     
  176.        {     
  177.            CvPoint* rect = pt;     
  178.            int count = 4;     
  179.              
  180.            // read 4 vertices     
  181.            memcpy( pt, reader.ptr, squares->elem_size );     
  182.            CV_NEXT_SEQ_ELEM( squares->elem_size, reader );     
  183.            memcpy( pt + 1, reader.ptr, squares->elem_size );     
  184.            CV_NEXT_SEQ_ELEM( squares->elem_size, reader );     
  185.            memcpy( pt + 2, reader.ptr, squares->elem_size );     
  186.            CV_NEXT_SEQ_ELEM( squares->elem_size, reader );     
  187.            memcpy( pt + 3, reader.ptr, squares->elem_size );     
  188.            CV_NEXT_SEQ_ELEM( squares->elem_size, reader );     
  189.              
  190.            // draw the square as a closed polyline      
  191.            cvPolyLine( cpy, &rect, &count, 1, 1, CV_RGB(0,255,0), 3, CV_AA, 0 );     
  192.        }     
  193.          
  194.        // show the resultant image     
  195.        cvShowImage( wndname, cpy );     
  196.        cvReleaseImage( &cpy );     
  197. }     
  198.     
  199.     
  200. void on_trackbar( int a )     
  201. {     
  202.        if( img )     
  203.            drawSquares( img, findSquares4( img, storage ) );     
  204. }     
  205.     
  206. char* names[] = { "E:\\1.jpg""E:\\2.jpg""E:\\3.jpg",     
  207.                      "E:\\4.jpg""E:\\5.jpg", 0 };     
  208.     
  209. int main(int argc, char** argv)     
  210. {     
  211.        int i, c;     
  212.        // create memory storage that will contain all the dynamic data     
  213.        storage = cvCreateMemStorage(0);     
  214.     
  215.        for( i = 0; names[i] != 0; i++ )     
  216.        {     
  217.            // load i-th image     
  218.            img0 = cvLoadImage( names[i], 1 );     
  219.            if( !img0 )     
  220.            {     
  221.                printf("Couldn't load %s\n", names[i] );     
  222.                continue;     
  223.            }     
  224.            img = cvCloneImage( img0 );     
  225.              
  226.            // create window and a trackbar (slider) with parent "image" and set callback     
  227.            // (the slider regulates upper threshold, passed to Canny edge detector)      
  228.            cvNamedWindow( wndname,0 );     
  229.            cvCreateTrackbar( "canny thresh", wndname, &thresh, 1000, on_trackbar );     
  230.              
  231.            // force the image processing     
  232.            on_trackbar(0);     
  233.            // wait for key.     
  234.            // Also the function cvWaitKey takes care of event processing     
  235.            c = cvWaitKey(0);     
  236.            // release both images     
  237.            cvReleaseImage( &img );     
  238.            cvReleaseImage( &img0 );     
  239.            // clear memory storage - reset free space position     
  240.            cvClearMemStorage( storage );     
  241.            if( c == 27 )     
  242.                break;     
  243.        }     
  244.          
  245.        cvDestroyWindow( wndname );     
  246.          
  247.        return 0;     
  248. }     
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值