资源描述:
《opencv 检测直线、线段、圆、矩形》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、opencv检测直线、线段、圆、矩形检测直线:cvHoughLines,cvHoughLines2检测圆:cvHoughCircles检测矩形:opencv中没有对应的函数,下面有段代码可以检测矩形,是通过先找直线,然后找到直线平行与垂直的四根线。检测直线代码:/*Thisisastandaloneprogram.Passanimagenameasafirstparameteroftheprogram.SwitchbetweenstandardandprobabilisticHoughtransformbychangi
2、ng"#if1"to"#if0"andback*/#include#include#includeintmain(intargc,char**argv){constchar*filename=argc>=2?argv[1]:"pic1.png";IplImage*src=cvLoadImage(filename,0);IplImage*dst;IplImage*color_dst;CvMemStorage*storage=cvCreateMemStorage(0);Cv
3、Seq*lines=0;inti;if(!src)return-1;dst=cvCreateImage(cvGetSize(src),8,1);color_dst=cvCreateImage(cvGetSize(src),8,3);cvCanny(src,dst,50,200,3);cvCvtColor(dst,color_dst,CV_GRAY2BGR);#if0lines=cvHoughLines2(dst,storage,CV_HOUGH_STANDARD,1,CV_PI/180,100,0,0);for(i=0
4、;itotal,100);i++){float*line=(float*)cvGetSeqElem(lines,i);floatrho=line[0];floattheta=line[1];CvPointpt1,pt2;doublea=cos(theta),b=sin(theta);doublex0=a*rho,y0=b*rho;pt1.x=cvRound(x0+1000*(-b));pt1.y=cvRound(y0+1000*(a));pt2.x=cvRound(x0-1000*(-b));p
5、t2.y=cvRound(y0-1000*(a));cvLine(color_dst,pt1,pt2,CV_RGB(255,0,0),3,CV_AA,0);}#elselines=cvHoughLines2(dst,storage,CV_HOUGH_PROBABILISTIC,1,CV_PI/180,50,50,10);for(i=0;itotal;i++){CvPoint*line=(CvPoint*)cvGetSeqElem(lines,i);cvLine(color_dst,line[0],lin
6、e[1],CV_RGB(255,0,0),3,CV_AA,0);}#endifcvNamedWindow("Source",1);cvShowImage("Source",src);cvNamedWindow("Hough",1);cvShowImage("Hough",color_dst);cvWaitKey(0);return0;}检测圆代码:#include#include#includeintmain(intargc,char**argv){IplImage*i
7、mg;if(argc==2&&(img=cvLoadImage(argv[1],1))!=0){IplImage*gray=cvCreateImage(cvGetSize(img),8,1);CvMemStorage*storage=cvCreateMemStorage(0);cvCvtColor(img,gray,CV_BGR2GRAY);cvSmooth(gray,gray,CV_GAUSSIAN,9,9);//smoothit,otherwisealotoffalsecirclesmaybedetectedCvS
8、eq*circles=cvHoughCircles(gray,storage,CV_HOUGH_GRADIENT,2,gray->height/4,200,100);inti;for(i=0;itotal;i++){float*p=(float*)cvGetSeqElem(circles,i);cvCircle