# OpenCV 霍夫变换

331人阅读 评论(0)

## 二. 实验代码

//霍夫变换
public:
void deal() {

imshow("霍夫变换[原图]", src_img);

Mat gray_img;
cvtColor(src_img, gray_img, COLOR_BGR2GRAY);

Mat mid_img;
Canny(gray_img, mid_img, 50, 200, 3);
imshow("边缘检测", mid_img);

vector<Vec2f> lines1;

HoughLines(mid_img, lines1, 1, CV_PI / 180, 150, 0, 0);

Mat out1;
out1.create(gray_img.size(), gray_img.type());
for (int i = 0; i < lines1.size(); ++i) {
double rho = lines1[i][0], theta = lines1[i][1];
Point p1, p2;
double a = cos(theta), b = sin(theta);
double x0 = a * rho, y0 = b * rho;
p1.x = cvRound(x0 + 1000 * (-b));
p1.y = cvRound(y0 + 1000 * a);
p2.x = cvRound(x0 - 1000 * (-b));
p2.y = cvRound(y0 - 1000 * a);
line(out1, p1, p2, 255, 1, LINE_AA);
}

imshow("霍夫变换[效果图1]", out1);

vector<Vec4i> lines2;
Mat out2;
out2.create(gray_img.size(), gray_img.type());
HoughLinesP(mid_img, lines2, 1, CV_PI / 180, 80, 50, 10);
for (int i = 0; i < lines2.size(); ++i) {
Vec4i l = lines2[i];
line(out2, Point(l[0], l[1]), Point(l[2], l[3]), 255, 1, LINE_AA);
}
imshow("霍夫变换[效果图2]", out2);

imshow("霍夫圆变换[原图]", src_img2);
Mat gray_img2;
cvtColor(src_img2, gray_img2, COLOR_BGR2GRAY);
GaussianBlur(gray_img2, gray_img2, Size(3, 3), 2, 2);

vector<Vec3f> circles;
HoughCircles(gray_img2, circles, HOUGH_GRADIENT, 1.5, 10, 200, 100, 0, 0);

Mat out3;
out3.create(gray_img2.size(), gray_img2.type());
for (int i = 0; i < circles.size(); ++i) {
Point center(cvRound(circles[i][0]), cvRound(circles[i][1]));
circle(out3, center, radius, 255, 3, 8, 0);
}
imshow("霍夫圆变换[效果图]", out3);

waitKey(0);
}
};


0
0

个人资料
• 访问：156888次
• 积分：3614
• 等级：
• 排名：第10768名
• 原创：213篇
• 转载：3篇
• 译文：0篇
• 评论：43条
最新评论