霍夫变换用于直线检测:
#include<opencv2/opencv.hpp> #include<opencv2/highgui/highgui.hpp> #include<iostream> using namespace cv; using namespace std; int main(){ Mat srcImage=imread("line.jpg",1); Mat dstImage1,dstImage2; Canny(srcImage,dstImage1,150,200,3); imshow("1",dstImage1); cvtColor(dstImage1,dstImage2,CV_GRAY2BGR); vector<Vec2f>lines; HoughLines(dstImage1,lines,1,CV_PI/180,120,0,0); for(size_t i=0;i<lines.size();i++){ float rho=lines[i][0],theta=lines[i][1]; Point pt1,pt2; double a=cos(theta),b=sin(theta); double x0=a*rho,y0=b*rho; int N=500; pt1.x=cvRound(x0+N*(-b)); pt2.y=cvRound(y0+N*(a)); pt2.x=cvRound(x0-N*(-b)); pt2.y=cvRound(y0-N*(a)); line(dstImage2,pt1,pt2,Scalar(0,255,0),1,CV_AA); } imshow("11",dstImage2); waitKey(0); }
圆形检测:
#include<opencv2/opencv.hpp> #include<opencv2/highgui/highgui.hpp> #include<iostream> using namespace cv; using namespace std; int main(){ Mat srcImage=imread("circle.jpg",1); imshow("0",srcImage); vector<Vec3f>circles; Mat grayImage; cvtColor(srcImage,grayImage,CV_BGR2GRAY); HoughCircles(grayImage,circles,CV_HOUGH_GRADIENT,1,10,200,44,0,0); for(size_t i=0;i<circles.size();i++){ Point center(cvRound(circles[i][0]),cvRound(circles[i][1])); int radius=cvRound(circles[i][2]); circle(srcImage,center,radius,Scalar(0,0,255),4); } imshow("1",srcImage); waitKey(0); }