第六章/图像变换 霍夫线变换
//2010年12月14日21:46:34
//rorger整理
//具体可以参考帮助手册
利用 Hough 变换在二值图像中找到直线
CvSeq* cvHoughLines2( CvArr* image, void* line_storage, int method, double rho, double theta, int threshold, double param1=0, double param2=0 );
函数 cvHoughLines2 实现了用于线段检测的不同 Hough 变换方法. Example. 用 Hough transform 检测线段
#include "cv.h" #include "highgui.h" #include "math.h" int main(int argc, char ** argv) { IplImage * image = cvLoadImage(argv[1], 0) ; IplImage * dst = cvCreateImage(cvGetSize(image),8,1) ; /*IplImage * icanny=cvCreateImage(cvGetSize(image),8,1) ;*/ CvMemStorage * storage = cvCreateMemStorage(0) ; //we can do this /*cvSetImageCOI(icanny,0) ; cvCvtColor(image,icanny,CV_BGR2GRAY); cvCanny(icanny,dst,50,150);*/ //or we can do this only cvCanny(image,dst,50,150); CvSeq * results= cvHoughLines2(dst,storage, CV_HOUGH_STANDARD,1,CV_PI/180,100,20,30); for(int i = 0 ; i < results ->total ; i ++) { float * lines = (float*) cvGetSeqElem(results, i) ; float rho =lines[0] ; float theta=lines[1]; CvPoint pt1,pt2 ; double a = cos(theta),b=sin(theta) ; if(fabs(a)<0.001) { pt1.x = pt2.x = cvRound(rho) ; pt1.y=0 ; pt2.y=dst->height; } else if(fabs(b)<0.001) { pt1.y = pt2.y = cvRound(rho) ; pt1.x=0 ; pt2.x = dst->width; } else { pt1.x=0; pt1.y=cvRound(rho/b) ; pt2.x=cvRound(rho/a) ; pt2.y=0 ; } cvLine(dst,pt1,pt2,CV_RGB(125,125,125),2); } cvNamedWindow("Source") ; cvNamedWindow("cvHoughLines",1) ; cvShowImage("cvHoughLines",dst); cvShowImage("Source",image); cvWaitKey(0) ; }
下面是木箱的图片: