您的位置:首页 > 运维架构

【OpenCV学习笔记】二十、霍夫变换及应用

2017-03-18 17:38 369 查看
霍夫变换

1.标准霍夫变换-HoughLines()

2.累计概率霍夫变换-HoughLinesP()

3.霍夫圆变换-HoughCircles()

先上ppt:



























代码:

#include "opencv2/opencv.hpp"

using namespace cv;

void main()
{
///标准霍夫变换-HoughLines()
//Mat src = imread("1.png");
//Mat dstImg = src.clone();
//imshow("src", src);
////霍夫变换是一种寻找直线的方法,一般在使用霍夫变换前首先将图像进行边缘检测处理,一般霍夫变换的输入为边缘二值图
//cvtColor(src, src, CV_BGR2GRAY);
//Mat cannyImg;
//Canny(src, cannyImg, 50, 200, 3);
//imshow("Canny", cannyImg);
//vector<Vec2f> lines; //定义矢量结构lines用于存放得到的线段矢量(ρ,θ)集合
//HoughLines(
// cannyImg,//输入原图像
// lines,//输出矢量集合(ρ,θ)
// 1, //以1像素点为单位的距离精度
// CV_PI / 180,//以1弧度为单位的角度精度
// 150//阈值,大于阈值的线段才可以被检测通过并返回到结果中
// );
//将线段画在目标图像上
//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;
// pt1.x = cvRound(x0 + 1000 * (-b));
// pt1.y = cvRound(y0 + 1000 * (a));
// pt2.x = cvRound(x0 - 1000 * (-b));
// pt2.y = cvRound(y0 - 1000 * (a));
// line(dstImg, pt1, pt2, Scalar(0, 0, 255), 1, CV_AA);
//}
//imshow("dst", dstImg);

//waitKey(0);
//destroyAllWindows();
///累计概率霍夫变换-HoughLinesP()
//Mat cannyImg;
//Mat src = imread("1.png");
//Mat dstImg = src.clone();
//imshow("src", src);

//cvtColor(src, src, CV_BGR2GRAY);
//Canny(src, cannyImg, 50, 200, 3);
//vector<Vec4i> lines; //定义矢量结构lines用于存放得到的线段矢量(x_1,y_1,x_2,y_2)集合
//HoughLinesP(cannyImg, lines, 1, CV_PI/180, 150, 50, 10);
////将线段画在目标图像上
//for(size_t i = 0; i<lines.size(); i++)
//{
// Vec4i l = lines[i];
// line(dstImg, Point(l[0], l[1]), Point(l[2], l[3]), Scalar(0, 255, 0), 2, CV_AA);
//}
//imshow("dst", dstImg);
//waitKey(0);
//destroyAllWindows();

///霍夫圆变换-HoughCircles()
Mat src = imread("C.JPG");
Mat dst = src.clone();
imshow("src", src);
cvtColor(src, src, CV_BGR2GRAY);
GaussianBlur(src, src, Size(9, 9), 2, 2);//不滤波会有非常非常多的误检圆
vector<Vec3f> circles;//存放经霍夫变换后检测出的圆的输出矢量(x,y,radius)
HoughCircles(src, circles, CV_HOUGH_GRADIENT, 2, 30, 200, 100, 10, 200);
//将圆画在目标图像上
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(dst, center, 3, Scalar(0, 0, 255), -1, 8, 0);
circle(dst, center, radius, Scalar(0, 255, 0), 3, 8, 0);
}
imshow("dst", dst);
waitKey(0);
}运行结果:
标准霍夫变换-HoughLines():







累计概率霍夫变换-HoughLinesP():







霍夫圆变换-HoughCircles():



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: