Use the OpenCV functions HoughLines and HoughLinesP to detect lines in an image.
主要用于通过已知点检测线段(相交认为一个线段),通常在简单的图像或边缘检测后应用图像的线检测。
#include "cv.h"
#include "highgui.h"
using namespace std;
using namespace cv;
int main(int argc,char *argv[])
{
Mat src,dst,dstColor;
src=imread("src.bmp",0);
Canny(src,dst,30,120,3);
imshow("dst",dst);
cvtColor(dst,dstColor,CV_GRAY2BGR);
vector<Vec2f> lines;
HoughLines(dst,lines,1,CV_PI/180,65);
cout<<lines.size()<<endl;
for (size_t i=0;i<lines.size();i++)
{
<span style="white-space:pre"> float rho=lines[i][0],theta=lines[i][1];
<span style="white-space:pre"> </span>Point pt1,pt2;
<span style="white-space:pre"> </span>double a=cos(theta),b=sin(theta);
<span style="white-space:pre"> </span>double x0=a*rho,y0=b*rho;
<span style="white-space:pre"> </span>pt1.x=cvRound(x0+1000*(-b));
<span style="white-space:pre"> </span>pt1.y=cvRound(y0+1000*a);
<span style="white-space:pre"> </span>pt2.x=cvRound(x0-1000*(-b));
<span style="white-space:pre"> </span>pt2.y=cvRound(y0-1000*a);
<span style="white-space:pre"> </span>line(dstColor,pt1,pt2,Scalar(255,0,0),1);</span>
}
imshow("dstColor",dstColor);
waitKey(0);
destroyAllWindows();
return 0;
}
实验效果:
当然可以使用更简单的:
#include "cv.h"
#include "highgui.h"
using namespace std;
using namespace cv;
int main(int argc,char *argv[])
{
Mat src,dst,dstColor;
src=imread("src.bmp",0);
Canny(src,dst,30,120,3);
imshow("dst",dst);
cvtColor(dst,dstColor,CV_GRAY2BGR);
vector<Vec4i> lines;
HoughLinesP(dst,lines,1,CV_PI/180,65);
cout<<lines.size()<<endl;
for (size_t i=0;i<lines.size();i++)
{
Vec4i l=lines[i];
line(dstColor,Point(l[0],l[1]),Point(l[2],l[3]),Scalar(255,0,0),1);
}
imshow("dstColor",dstColor);
waitKey(0);
destroyAllWindows();
return 0;
}
实验效果:
重要函数
更简单的:
Use the OpenCV function HoughCircles to detect circles in an image.
#include "cv.h"
#include "highgui.h"
using namespace std;
using namespace cv;
int main(int argc,char *argv[])
{
Mat src,srcGray;
src=imread("a.jpg");
cvtColor(src,srcGray,CV_BGR2GRAY);
GaussianBlur(srcGray,srcGray,Size(3,3),0,0);
vector<Vec3f> circles;
HoughCircles(srcGray,circles,CV_HOUGH_GRADIENT,1,srcGray.rows/8,60,30);
cout<<circles.size()<<endl;
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(src,center,3,Scalar(0,255,0),CV_FILLED);
circle(src,center,radius,Scalar(0,0,255));
}
imshow("src",src);
waitKey(0);
destroyAllWindows();
return 0;
}
重要函数:
实验效果: