`
睡着的兔子
  • 浏览: 34474 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

ZZ opencv 识别图像中的四边形的代码

阅读更多
#include "stdafx.h"

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


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;
	   //1e-10就是“aeb”的形式,表示a乘以10的b次方。
       //其中b必须是整数,a可以是小数。
	   //?余弦定理CosB=(a^2+c^2-b^2)/2ac??所以这里的计算似乎有问题
       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
       //使用gaussian金字塔分解对输入图像向下采样,首先对它输入的图像用指定滤波器
	   //进行卷积,然后通过拒绝偶数的行与列来下采样
	   cvPyrDown( timg, pyr, 7 );
       //函数 cvPyrUp 使用Gaussian 金字塔分解对输入图像向上采样。首先通过在图像中插入 0 偶数行和偶数列,然后对得到的图像用指定的滤波器进行高斯卷积,其中滤波器乘以4做插值。所以输出图像是输入图像的 4 倍大小。
	   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 基于给定的值设置感兴趣的通道。值 0 意味着所有的通道都被选定, 1 意味着第一个通道被选定等等。
           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,60, 180, 3 );
                   // 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 );
       cvThreshold( tgray, gray, 50, 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
				   //cvContourArea 计算整个轮廓或部分轮廓的面积
                   //cvCheckContourConvexity测试轮廓的凸性                  
				   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[] = { "E:\\1.jpg", "E:\\2.jpg", "E:\\3.jpg",
                     "E:\\4.jpg", "E:\\5.jpg", 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,0 );
           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;
}


 

这个程序的基本思想是:对输入的图像进行滤波去掉噪音,然后进行canny边缘检测,之后进行膨胀,然后寻找轮廓,对轮廓进行多边形的逼近,检测多边形的点数是否是4而且各个角的的余弦是否是小于某个值,程序中认为是0.3,然后就判断该多边形是四边形,之后根据这四个点画出该图像。

ps:我对程序中余弦定理的使用 感觉公式用错了

转自:http://hi.baidu.com/%B7%E7%B4%B5%B2%DD%B5%CD%BC%FB%C5%A3%B1%C6/blog/item/e8a54ff48ed4626fddc474a5.html

分享到:
评论
1 楼 qaz143109 2014-04-21  
谢谢 余弦那个对的 是向量夹角公式  不是三角形余弦定理
cos<a,b>=(ab的内积)/(|a||b|)

相关推荐

    基于opencv的图像识别,识别图像中的色块

    本教程将聚焦于如何利用OpenCV实现图像识别,特别是识别图像中的特定颜色块,如红色、绿色和蓝色。这个过程涉及到色彩空间转换、二值化等关键技术。 首先,我们要了解OpenCV中的色彩空间。在OpenCV中,图像默认存储...

    VS C# OpenCV图像识别+文字打印

    【标题】"VS C# OpenCV图像识别+文字打印"涉及的是使用Visual Studio(VS)2013、C#编程语言以及OpenCV库进行图像处理和识别的应用。OpenCV是一个开源的计算机视觉库,它提供了丰富的功能,包括图像处理、特征检测、...

    基于opencv 的四边形轮廓跟踪

    我们将深入探讨如何在OpenCV中实现四边形轮廓的识别和追踪。 首先,我们需要理解轮廓的概念。在图像处理中,轮廓是对象边界在二值图像上的表现。当图像被转化为黑白二值图像后,我们可以通过查找连续的像素变化来...

    Python Opencv实现图像轮廓识别功能

    本文实例为大家分享了python opencv识别图像轮廓的具体代码,供大家参考,具体内容如下 要求:用矩形或者圆形框住图片中的云朵(不要求全部框出) 轮廓检测 Opencv-Python接口中使用cv2.findContours()函数来查找...

    基于opencv图像轮廓识别代码

    【标题】"基于opencv图像轮廓识别代码"是一个关于在Linux环境下使用OpenCV库进行图像处理,特别是轮廓检测的项目。OpenCV(Open Source Computer Vision Library)是一个强大的计算机视觉和机器学习软件库,广泛应用...

    VC +opencv识别图像中图形显示于界面

    在本文中,我们将深入探讨如何使用Visual C++(VC++)结合OpenCV库来实现图像中的图形识别,并将识别结果在用户界面中展示出来。OpenCV(开源计算机视觉库)是一个强大的工具,它提供了丰富的功能,包括图像处理、模式...

    基于OpenCV的图像锐化 C代码

    包含代码以及讲解ppt

    基于OpenCV的图像识别及跟踪程序

    总之,基于OpenCV的图像识别及跟踪程序涉及到多个计算机视觉的关键技术,包括图像预处理、特征提取、目标检测、识别、跟踪以及实际应用中的性能优化。通过学习和掌握这些知识点,开发者可以创建出高效且精确的视觉...

    c# opencv条码识别参考代码

    4. **轮廓检测**:OpenCV的`FindContours`函数可用于检测图像中的闭合形状,这在识别条码的边界框时非常有用。 5. **模板匹配**:在某些情况下,可以使用OpenCV的模板匹配功能来查找图像中与条码模板相似的部分。 ...

    sp.rar_OpenCV图像识别_opencv 图像识别_图像识别_识别

    本教程将深入探讨OpenCV在图像识别中的应用,以及如何利用它来实现图像和视频的识别。 首先,让我们了解OpenCV的基本概念。OpenCV是由Intel公司发起并维护的一个开源项目,它提供了C++、Python等多种编程语言接口,...

    基于OpenCV的图像处理代码

    在这个“基于OpenCV的图像处理代码”中,我们可以看到开发者使用OpenCV实现了基本的图像操作,例如阈值分割。 阈值分割是图像处理中的一个关键步骤,用于将图像二值化,即将图像中的像素点根据某个阈值分为两类,...

    opencv水果识别样本(苹果、香蕉、梨子)

    OpenCV(开源计算机视觉库)是一个强大的图像处理和计算机视觉工具,广泛应用于图像识别、物体检测、人脸识别等领域。在这个特定的“opencv水果识别样本(苹果、香蕉、梨子)”项目中,我们关注的是如何利用OpenCV来...

    人脸识别(基于OpenCv 完整代码)

    OpenCV中常用的人脸检测方法是Haar级联分类器,它通过训练得到的XML文件来识别图像中的脸部特征。 2. **特征提取**:一旦检测到人脸,就需要提取出人脸的特征。常见的特征提取方法有Eigenfaces、Fisherfaces和Local...

    基于opencv的图像增强函数(c++)

    基于opencv的图像增强函数,Demo用vc6.0实现。 如果您对安装opencv或在vc6.0下配置opencv有疑问,请访问opencv中文网站: http://www.opencv.org.cn/

    基于OpenCV的红点识别

    在这个“基于OpenCV的红点识别”项目中,我们将深入探讨如何利用OpenCV来检测和识别图像中的红色像素点,这对于目标识别和跟踪等应用具有实际意义。 首先,我们要了解OpenCV的基本概念。OpenCV是一个跨平台的库,...

    基于Opencv的图像缺陷识别简单例子

    本项目提供了一个基于OpenCV的图像缺陷识别的简单示例,这可以帮助初学者理解如何利用OpenCV进行图像分析。 1. **OpenCV基础**: OpenCV是一个跨平台的库,它包含了大量的函数,用于实时的图像处理、计算机视觉和...

    opencv指纹识别FVS_opencv_指纹识别_VC++

    在指纹识别系统中,OpenCV可以帮助我们完成图像预处理、特征提取以及匹配等多个关键步骤。 1. **图像预处理**:指纹图像通常会包含噪声和不清晰的区域。OpenCV提供了一系列函数,如直方图均衡化、二值化、腐蚀和...

    python opencv判断图像是否为空的实例

    如下所示: import cv2 im = cv2.imread('2.jpg') ... 您可能感兴趣的文章:ubuntu下编译安装opencv的方法Opencv+Python实现图像运动模糊和高斯模糊的示例OpenCV HSV颜色识别及HSV基本颜色分量范围基于Ope

    opencv vc++ c+ 图像倾斜校正

    在VC++环境中,你需要将OpenCV库链接到你的项目中,并使用OpenCV的C++接口编写代码来实现上述步骤。确保正确配置编译器和链接器设置,以避免运行时错误。 在实际应用中,可能还需要考虑其他因素,如图像缩放、填充...

    基于OpenCV的图像检索系统(源码)

    **基于OpenCV的图像检索系统**是计算机视觉领域的一个重要应用,主要目的是通过特定的算法在大量图像数据库中快速找到与目标图像相似的图像。在这个系统中,我们使用了OpenCV(开源计算机视觉库)这一强大的工具,它...

Global site tag (gtag.js) - Google Analytics