如何检测和处理轮廓线 squares demo

转载 2012年03月29日 17:05:59
/*
在程序里找寻矩形
*/
#ifdef _CH_
#pragma package <opencv>
#endif

#ifndef _EiC
#include "cv.h"
#include "highgui.h"
#include <stdio.h>
#include <math.h>
#include <string.h>
#endif

int thresh = 50;
IplImage* img = 0;
IplImage* img0 = 0;
CvMemStorage* storage = 0;
CvPoint pt[4];
const char* wndname = "Square Detection Demo";

// helper function:
// finds a cosine of angle between vectors
// from pt0->pt1 and from pt0->pt2 
double angle( CvPoint* pt1, CvPoint* pt2, CvPoint* 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);
}

// returns sequence of squares detected on the image.
// the sequence is stored in the specified memory storage
CvSeq* findSquares4( IplImage* img, CvMemStorage* storage )
{
    CvSeq* contours;
    int i, c, l, N = 11;
    CvSize sz = cvSize( img->width & -2, img->height & -2 );
    IplImage* timg = cvCloneImage( img ); // make a copy of input image
    IplImage* gray = cvCreateImage( sz, 8, 1 ); 
    IplImage* pyr = cvCreateImage( cvSize(sz.width/2, sz.height/2), 8, 3 );
    IplImage* tgray;
    CvSeq* result;
    double s, t;
    // create empty sequence that will contain points -
    // 4 points per square (the square's vertices)
    CvSeq* squares = cvCreateSeq( 0, sizeof(CvSeq), sizeof(CvPoint), storage );
    
    // select the maximum ROI in the image
    // with the width and height divisible by 2
    cvSetImageROI( timg, cvRect( 0, 0, sz.width, sz.height ));
    
    // down-scale and upscale the image to filter out the noise
    cvPyrDown( timg, pyr, 7 );
    cvPyrUp( pyr, timg, 7 );
    tgray = cvCreateImage( sz, 8, 1 );
    
    // find squares in every color plane of the image
    for( c = 0; c < 3; c++ )
    {
        // extract the c-th color plane
        cvSetImageCOI( timg, c+1 );
        cvCopy( timg, tgray, 0 );
        
        // try several threshold levels
        for( l = 0; l < N; l++ )
        {
            // hack: use Canny instead of zero threshold level.
            // Canny helps to catch squares with gradient shading   
            if( l == 0 )
            {
                // apply Canny. Take the upper threshold from slider
                // and set the lower to 0 (which forces edges merging) 
                cvCanny( tgray, gray, 0, thresh, 5 );
                // dilate canny output to remove potential
                // holes between edge segments 
                cvDilate( gray, gray, 0, 1 );
            }
            else
            {
                // apply threshold if l!=0:
                //     tgray(x,y) = gray(x,y) < (l+1)*255/N ? 255 : 0
                cvThreshold( tgray, gray, (l+1)*255/N, 255, CV_THRESH_BINARY );
            }
            
            // find contours and store them all as a list
            cvFindContours( gray, storage, &contours, sizeof(CvContour),
                CV_RETR_LIST, CV_CHAIN_APPROX_SIMPLE, cvPoint(0,0) );
            
            // test each contour
            while( contours )
            {
                // approximate contour with accuracy proportional
                // to the contour perimeter
                result = cvApproxPoly( contours, sizeof(CvContour), storage,
                    CV_POLY_APPROX_DP, cvContourPerimeter(contours)*0.02, 0 );
                // square contours should have 4 vertices after approximation
                // relatively large area (to filter out noisy contours)
                // and be convex.
                // Note: absolute value of an area is used because
                // area may be positive or negative - in accordance with the
                // contour orientation
                if( result->total == 4 &&
                    fabs(cvContourArea(result,CV_WHOLE_SEQ)) > 1000 &&
                    cvCheckContourConvexity(result) )
                {
                    s = 0;
                    
                    for( i = 0; i < 5; i++ )
                    {
                        // find minimum angle between joint
                        // edges (maximum of cosine)
                        if( i >= 2 )
                        {
                            t = fabs(angle(
                            (CvPoint*)cvGetSeqElem( result, i ),
                            (CvPoint*)cvGetSeqElem( result, i-2 ),
                            (CvPoint*)cvGetSeqElem( result, i-1 )));
                            s = s > t ? s : t;
                        }
                    }
                    
                    // if cosines of all angles are small
                    // (all angles are ~90 degree) then write quandrange
                    // vertices to resultant sequence 
                    if( s < 0.3 )
                        for( i = 0; i < 4; i++ )
                            cvSeqPush( squares,
                                (CvPoint*)cvGetSeqElem( result, i ));
                }
                
                // take the next contour
                contours = contours->h_next;
            }
        }
    }
    
    // release all the temporary images
    cvReleaseImage( &gray );
    cvReleaseImage( &pyr );
    cvReleaseImage( &tgray );
    cvReleaseImage( &timg );
    
    return squares;
}

// the function draws all the squares in the image
void drawSquares( IplImage* img, CvSeq* squares )
{
    CvSeqReader reader;
    IplImage* cpy = cvCloneImage( img );
    int i;
    
    // initialize reader of the sequence
    cvStartReadSeq( squares, &reader, 0 );
    
    // read 4 sequence elements at a time (all vertices of a square)
    for( i = 0; i < squares->total; i += 4 )
    {
        CvPoint* rect = pt;
        int count = 4;
        
        // read 4 vertices
        memcpy( pt, reader.ptr, squares->elem_size );
        CV_NEXT_SEQ_ELEM( squares->elem_size, reader );
        memcpy( pt + 1, reader.ptr, squares->elem_size );
        CV_NEXT_SEQ_ELEM( squares->elem_size, reader );
        memcpy( pt + 2, reader.ptr, squares->elem_size );
        CV_NEXT_SEQ_ELEM( squares->elem_size, reader );
        memcpy( pt + 3, reader.ptr, squares->elem_size );
        CV_NEXT_SEQ_ELEM( squares->elem_size, reader );
        
        // draw the square as a closed polyline 
        cvPolyLine( cpy, &rect, &count, 1, 1, CV_RGB(0,255,0), 3, CV_AA, 0 );
    }
    
    // show the resultant image
    cvShowImage( wndname, cpy );
    cvReleaseImage( &cpy );
}

void on_trackbar( int a )
{
    if( img )
        drawSquares( img, findSquares4( img, storage ) );
}

char* names[] = { "pic1.png", "pic2.png", "pic3.png",
                  "pic4.png", "pic5.png", "pic6.png", 0 };

int main(int argc, char** argv)
{
    int i, c;
    // create memory storage that will contain all the dynamic data
    storage = cvCreateMemStorage(0);

    for( i = 0; names[i] != 0; i++ )
    {
        // load i-th image
        img0 = cvLoadImage( names[i], 1 );
        if( !img0 )
        {
            printf("Couldn't load %s\n", names[i] );
            continue;
        }
        img = cvCloneImage( img0 );
        
        // create window and a trackbar (slider) with parent "image" and set callback
        // (the slider regulates upper threshold, passed to Canny edge detector) 
        cvNamedWindow( wndname, 1 );

		// int cvCreateTrackbar( const char* trackbar_name, const char* window_name,
		//int* value, int count, CvTrackbarCallback on_change );
		//trackbar_name
		//被创建的trackbar名字。 
		//window_name
		//窗口名字,这个窗口将为被创建trackbar的父对象。 
		//value 
		//整数指针,它的值将反映滑块的位置。这个变量指定创建时的滑块位置。 
		//count 
		//滑块位置的最大值。最小值一直是0。 
		//on_change 
		//每次滑块位置被改变的时候,被调用函数的指针。这个函数应该被声明为void Foo(int); 
		//如果没有回调函数,这个值可以设为NULL。 
		//函数cvCreateTrackbar用指定的名字和范围来创建trackbar(滑块或者范围控制),
		//指定与trackbar位置同步的变量,并且指定当trackbar位置被改变的时候调用的回调函数。
		//被创建的trackbar显示在指定窗口的顶端。 
        cvCreateTrackbar( "canny thresh", wndname, &thresh, 1000, on_trackbar );
        
        // force the image processing
        on_trackbar(0);
        // wait for key.
        // Also the function cvWaitKey takes care of event processing
        c = cvWaitKey(0);
        // release both images
        cvReleaseImage( &img );
        cvReleaseImage( &img0 );
        // clear memory storage - reset free space position
        cvClearMemStorage( storage );
        if( c == 27 )
            break;
    }
    
    cvDestroyWindow( wndname );  
    return 0;
}

#ifdef _EiC
main(1,"squares.c");
#endif

相关文章推荐

UE4中多种颜色轮廓线的后期处理

随着近来虚幻引擎4的一些变化,渲染多种颜色的轮廓线已经可以实现了!通过自定义模板,类似自定义深度的缓冲区——但允许网格作为整数值来渲染。它提供了一个0~255范围,可以在网格上定义不同颜色的轮廓线,甚...

提取矢量物体轮廓线

  • 2015年08月22日 15:21
  • 1.85MB
  • 下载

POJ2411 - Mondriaan's Dream (状压DP+轮廓线DP)

题目链接:http://poj.org/problem?id=2411题目大意:这题题意非常明确,现在有一个 M × N 的矩形,你现在有很多个 2 × 1 大小的方块,现在要用这些方块铺满这个矩形,...

dwg搜索闭合轮廓线

  • 2010年10月13日 15:14
  • 217KB
  • 下载

【轮廓线DP,状压DP】BZOJ1087 [SCOI2005]互不侵犯King

题面在这里轮廓线DP的经典题……可以发现,对于当前点(i,j),只有前面n+1个格子与其有关(如下图) 那么这n+1个位置就是(i,j)的轮廓线。 把轮廓线上的状态用位运算压缩一下即可。f[c...
  • linkfqy
  • linkfqy
  • 2017年06月09日 08:08
  • 691

正面人脸轮廓线多模板提取方法

  • 2014年07月15日 11:22
  • 2.51MB
  • 下载

poj2411 Mondriaan's Dream(轮廓线动态规划)

【题解】 首先将棋盘转化成"竖长形"(m 那么正枚举的当前行可能是参差不齐的,在当前行产生轮廓(用1/0表示当前是否被覆盖,若当前格选择填0,其上方相邻位必为1,否则再无法被覆盖) 以枚举格的坐标和当...
  • cjk_cjk
  • cjk_cjk
  • 2015年03月23日 00:35
  • 574
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:如何检测和处理轮廓线 squares demo
举报原因:
原因补充:

(最多只允许输入30个字)