OpenCV中cvHoughLines2和cvHoughCircles使用范例

cvHoughLines2和cvHoughCircles使用范例。有图,有程序。

cvHoughLines2需要的是Binary image。 cvHoughCircles 需要的是灰度图,而且它会自动调用cvSobel函数。

关于cvHoughCircles多说一句,之前最好用cvSmooth一下,否则会有很多错误的圆被识别出来。

cvHoughLines2
orginal

lines.jpg (99.05 KiB) 被浏览 4777 次


cvHoughCircles 
cccc1.jpg (12.69 KiB) 被浏览 4777 次

(VS2008+open1.1,注意图片路径)

#include "stdafx.h"
#include 

#include 
#include 
#include 
#include 
using namespace std;
/*
coded and updated by Huang, Haiqiao 2010-01-13
Examples of using cvHoughLines2 and cvHoughCircles
*/

int main(int argc, char** argv)
{
   int i;
   cout << "Lines and Circles OpenCV!"<width,imgGrey->height),IPL_DEPTH_8U,1);
   cvCanny(imgGrey,cannyImg,170,200,3);

   //************hough lines**probabilistic********//
   CvMemStorage* storage = cvCreateMemStorage(0);
        CvSeq* lines = 0; 
   double rho=1;
   double theta=CV_PI/180;
   double threshold=30;
   double min_length=40;//CV_HOUGH_PROBABILISTIC
   double sepration_connection=20;//CV_HOUGH_PROBABILISTIC

   //binary image is needed.
    lines = cvHoughLines2(
      cannyImg, 
      storage, 
      CV_HOUGH_PROBABILISTIC, 
      rho,
      theta, 
      threshold,
      min_length, 
      sepration_connection);

   //draw lines found by cvHoughLines2
    for( i = 0; i < lines->total; i++ )
    {
       CvPoint* line = (CvPoint*)cvGetSeqElem(lines,i);
       cvLine(imgRGB, line[0], line[1], CV_RGB(255,0,0),1, 8 );//cannyImgColor
    } 
   


   /*
      Circle identification
   */  
   IplImage* grayimgcircle = cvCreateImage( cvGetSize(imgcircle), 8, 1 );
   CvMemStorage* storagecircle = cvCreateMemStorage(0);
    cvCvtColor( imgcircle, grayimgcircle, CV_BGR2GRAY );
   // smooth it, otherwise a lot of false circles may be detected
    cvSmooth( grayimgcircle, grayimgcircle, CV_GAUSSIAN, 9, 9 ); 
    
   double dp=2;
   double min_dist=10;
   int min_radius=5;
   int max_radius=150; 
   //only greyimage is needed. cvHoughCircles would call cvSobel() internally.
   CvSeq* circles = cvHoughCircles( 
         grayimgcircle, 
         storagecircle, 
         CV_HOUGH_GRADIENT, 
         dp, 
         min_dist, 
         min_radius, 
         max_radius );

    //draw found curves
    for( i = 0; i < circles->total; i++ )
    {
         float* p = (float*)cvGetSeqElem( circles, i );
         cvCircle( imgcircle, cvPoint(cvRound(p[0]),cvRound(p[1])), cvRound(p[2]), CV_RGB(255,0,0), 3, 8, 0 );
    }
   


    cvNamedWindow( "Circles", CV_WINDOW_AUTOSIZE );
    cvShowImage( "Circles", imgcircle );
   cvNamedWindow("Original", CV_WINDOW_AUTOSIZE );
   cvShowImage( "Original", imgRGB );

   cvWaitKey(0);

   cvDestroyWindow("HoughLines");
   cvReleaseImage(&imgGrey);
   cvDestroyWindow("Original");
   cvReleaseImage(&imgcircle);
   cvDestroyWindow("Circles");
   
   //char c=getchar();
   return 0;
}


你可能感兴趣的:(OpenCV)