OpenCV 轮廓检测

使用OpenCV可以对图像的轮廓进行检测。这是之前用过的代码,挺简单的,回顾一下。主要要进行以下2步操作:

1.cvThreshold():对图像进行二值化处理

2.cvFindContours():查找图像轮廓

注意:这个过程中图像要转化为灰度图。


  1. #include "stdafx.h"  
  2. #include "cv.h"  
  3. #include "cxcore.h"  
  4. #include "highgui.h"  
  5.    
  6. int main( int argc, char** argv )  
  7. {  
  8.   //声明IplImage指针  
  9.   IplImage* pImg = NULL;   
  10.   IplImage* pContourImg = NULL;  
  11.    
  12.   CvMemStorage * storage = cvCreateMemStorage(0);  
  13.   CvSeq * contour = 0;  
  14.   int mode = CV_RETR_EXTERNAL;  
  15.    
  16.   if( argc == 3)  
  17.       if(strcmp(argv[2], "all") == 0)  
  18.     mode = CV_RETR_CCOMP; //内外轮廓都检测  
  19.    
  20.    
  21.   //创建窗口  
  22.   cvNamedWindow("src", 1);  
  23.   cvNamedWindow("contour",1);  
  24.   cvNamedWindow("threshold",1);  
  25.    
  26.    
  27.   //载入图像,强制转化为Gray  
  28.   if( argc >= 2 &&   
  29.       (pImg = cvLoadImage( argv[1], 0)) != 0 )  
  30.     {  
  31.    
  32.       cvShowImage( "src", pImg );  
  33.    
  34.       //为轮廓显示图像申请空间  
  35.       //3通道图像,以便用彩色显示  
  36.       pContourImg = cvCreateImage(cvGetSize(pImg),  
  37.                       IPL_DEPTH_8U,  
  38.                       3);  
  39.       //copy source image and convert it to BGR image  
  40.       cvCvtColor(pImg, pContourImg, CV_GRAY2BGR);  
  41. //----阈值分割-------------------------------------------  
  42.       cvThreshold( pImg, pImg, 150, 255, CV_THRESH_BINARY );  
  43.       cvShowImage( "threshold", pImg );  
  44. //-----------------------------------------------  
  45. //查找contour----------------输入必须是二值图像  
  46.       cvFindContours( pImg, storage, &contour, sizeof(CvContour),   
  47.           mode, CV_CHAIN_APPROX_SIMPLE, cvPoint(0,0));  
  48.    
  49.     }  
  50.   else  
  51.     {  
  52.       //销毁窗口  
  53.       cvDestroyWindow( "src" );  
  54.       cvDestroyWindow( "contour" );  
  55.       cvReleaseMemStorage(&storage);  
  56.    
  57.       return -1;  
  58.     }  
  59.    
  60.    
  61.    
  62.    
  63.   //将轮廓画出      
  64.   cvDrawContours(pContourImg, contour,   
  65.          CV_RGB(0,0,255), CV_RGB(255, 0, 0),   
  66.          2, 2, 8, cvPoint(0,0));  
  67.   //显示图像  
  68.   cvShowImage( "contour", pContourImg );  
  69.    
  70.   cvWaitKey(0);  
  71.    
  72.    
  73.   //销毁窗口  
  74.   cvDestroyWindow( "src" );  
  75.   cvDestroyWindow( "contour" );  
  76.   //释放图像  
  77.   cvReleaseImage( &pImg );   
  78.   cvReleaseImage( &pContourImg );   
  79.    
  80.   cvReleaseMemStorage(&storage);  
  81.    
  82.   return 0;  
  83. }  

源图像:


二值化以后:


轮廓:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值