对于HoughLine变换,有两种方法,标准霍夫变换(SHT)用的矩阵是CV_32FC2,用极坐标法记录直线,而累积概率霍夫变换(PPHT)用的是CV_32FC

核心函数:

cvCvtColor,cvHoughLines2,cvGetSeqElem

程序:

wKiom1PsLI3CA99pAATsEcm_K2Y879.jpg

代码:

#include "cv.h"
#include "cxcore.h"
#include "highgui.h"
#include <iostream>
int HoughLines(int argc,char** argv)
{
IplImage* src=cvLoadImage("e:\\picture\\8.JPG",0);
IplImage* canny=cvCreateImage(cvGetSize(src),8,1);
IplImage* result=cvCreateImage(cvGetSize(src),8,3);
IplImage* result2=cvCreateImage(cvGetSize(src),8,3);
CvSeq* line=0;
CvMemStorage* storage = cvCreateMemStorage(0);
cvCanny(src,canny,50,125); //找线段的图像必须先用cvCanny寻找轮廓
//查找直线
line=cvHoughLines2(canny,storage,CV_HOUGH_PROBABILISTIC,1, CV_PI/180, 80, 30, 10 );
cvCvtColor(canny,result,CV_GRAY2BGR);  //黑白转换为彩色
cvCopy(result,result2);
for(int i=0;i<line->total;i++)
{
CvPoint *pt=(CvPoint*)cvGetSeqElem(line,i);  //提取结果坐标
cvLine(result,pt[0],pt[1],cvScalar(0,0,255),3,8);
}
//查找圆
cvClearMemStorage(storage);
CvMemStorage* storage2 = cvCreateMemStorage(0);
cvSmooth(src,src,CV_GAUSSIAN,5,5);
line=cvHoughCircles(src,storage2,CV_HOUGH_GRADIENT,2,10);
for(int i=0;i<line->total;i++)
{
std::cout<<"circle"<<std::endl;
float *p=(float*)cvGetSeqElem(line,i);  //提取结果坐标
CvPoint pt=cvPoint(cvRound(p[0]),cvRound(p[1])); //p[0]和p[1]是圆心的x和y坐标,不过要四舍五入取整:cvRound
cvCircle(result2,pt,cvRound(p[2]),cvScalar(0,0,255),3,20);
}
cvNamedWindow("src");
cvNamedWindow("canny");
cvNamedWindow("result");
cvNamedWindow("result2");
cvShowImage("src",src);
cvShowImage("canny",canny);
cvShowImage("result",result);
cvShowImage("result2",result2);
cvWaitKey(0);
cvDestroyWindow("src");
cvDestroyWindow("canny");
cvDestroyWindow("result");
cvDestroyWindow("result2");
cvReleaseImage(&src);
cvReleaseImage(&canny);
cvReleaseImage(&result);
cvReleaseImage(&result2);
return 0;
}