/*

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

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

*/

#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;  

}

opencv识别四边形相关推荐

  1. 转载:使用 OpenCV 识别 QRCode

    原文链接:http://coolshell.cn/articles/10590.html#jtss-tsina 识别二维码的项目数不胜数,每次都是开箱即用,方便得很. 这次想用 OpenCV 从零识别 ...

  2. opencv resize_利用OpenCV 识别两张相似的图片

    Background: 在我们项目中,用到U-net,我们对训练样本图片使用labelme进行标定,对标定生成的json文件labelme_json_to_dataset生成标注图像,由于小伙伴将生成 ...

  3. opencv 取roi_利用OpenCV 识别两张相似的图片

    Background: 在我们项目中,用到U-net,我们对训练样本图片使用labelme进行标定,对标定生成的json文件labelme_json_to_dataset生成标注图像,由于小伙伴将生成 ...

  4. c++ 解析从浏览器端传过来的图像base64编码,并转换成opencv识别的格式

    from: c++ 解析从浏览器端传过来的图像base64编码,并转换成opencv识别的格式 #include <cstdint> #include <fstream> #i ...

  5. python相似图片识别_Python+Opencv识别两张相似图片

    Python+Opencv识别两张相似图片 在网上看到python做图像识别的相关文章后,真心感觉python的功能实在太强大,因此将这些文章总结一下,建立一下自己的知识体系. 当然了,图像识别这个话 ...

  6. Opencv识别面部

    Opencv识别面部 本文识别面部依然采用的是cv zone中的面部识别的模型. 安装Opencv pip install opencv-python 安装cvzone pip install cvz ...

  7. Python+OpenCV 识别银行卡卡号

    Python+OpenCV 识别银行卡卡号 今天尝试一下用python+OpenCV,使用模板匹配的方式做个简单地识别银行卡卡号(大部分参考网上的,自己改了一部分,代码写的有点不太好,但是思路很清晰, ...

  8. Opencv识别车牌

    Opencv识别车牌 #encoding:utf8 import cv2 import numpy as np Min_Area = 50 #定位车牌 def color_position(img,o ...

  9. 通过OpenCV识别QR二维码

    <OpenCV系列教程> 二维码有很多种,我们今天介绍的就是QR这种二维码,全名是 Quick Response Code,下面我们就称作QR码. 博客分为两部分,第一部分是QR码的基础知 ...

最新文章

  1. python进程池multiprocessing.Pool运行错误:The freeze_support() line can be omitted if the program is not g
  2. java rmi 使用方法
  3. [译] NSCollectionView 入门教程
  4. mysql 视图慢_第03问:磁盘 IO 报警,MySQL 读写哪个文件慢了?
  5. 同步模式下的端口映射程序
  6. Mysql从库主键卡住_从库宕机引发的主键冲突
  7. mysql 存储过程中limit
  8. LeetCode 1224. 最大相等频率(哈希)
  9. 去别人共享目录下拷贝东西,怎么进入别人的机器
  10. Linux学习笔记二:Ubuntu启用root用户、更改软件源以及安装vim
  11. 蓝桥杯2018年第九届C/C++省赛B组第二题-明码
  12. Swashbuckle Swagger组件扩展
  13. 浪潮gs设置连接服务器信息,浪潮GS系统客户端设置方案
  14. python批量音频转格式_ffmpeg 转为16K PCM格式,python生成批量转码脚本
  15. 主要空间数据挖掘方法
  16. 软件如何实现屏幕共享?
  17. 论文写作学习心得体会
  18. 【阿里102句土话集锦】菜鸟必备
  19. android手机电话铃声设置,怎么设置来电铃声-安卓手机小技巧:教你传输自己喜欢的歌曲铃声到系统铃声设置里...
  20. 阳春3月,这个技术博客要暂停1月!!!!

热门文章

  1. 面向机器学习的自然语言标注导读
  2. Apollo配置中心与本地配置优先级
  3. qq录屏快捷键是什么?qq录屏声音设置
  4. 学习可视采耳要多长时间?可视采耳学费要多少钱?开一家可视采耳店大概要多少钱?
  5. 3GPP R17空闲态省电特性
  6. 周明:预训练模型在多语言、多模态任务的进展
  7. VLAN是什么?划分VLAN的作用及方法
  8. 基于支持向量机 (SVM) 和稀疏表示理论 (SRC) 的人脸识别比较
  9. 哈希算法SHA-512
  10. 按名称排列时特殊符号排列顺序问题