本節主要介紹如何用Hough變換檢測直線和圓
一:Hough變換檢測直線
<1> 原始Hough變換
思想:先求出圖像中每點的極座標方程<如下圖>,相交於一點的極座標曲線的個數大於最小投票數,則將該點所對應的(p,
r0)放入vector中,即得到一條直線,lines中存儲的是極座標方程的參數
注意hough變換要求輸入的是包含一組點的二值圖像。
代碼:
-
Canny(image, result, 150, 220);
-
vector<Vec2f> lines;
-
HoughLines(result, lines, 1, PI/180, 120);
-
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(image, pt1, pt2, Scalar(255), 3, CV_AA);
-
}
其中1和PI/180是直線搜索是的步進尺寸。
結果:
canny後得結果:
hough變換後:
<2>概念Hough變換
思想:不是系統的進行掃描圖像,而是隨機挑選像素點,一旦累加器中某一項達到給定的最小值,那麼掃描沿着對應直線的像素並移除所有經過的像素點。得到的可以說是一條線段
獲得一條直線即將(x0, y0, x1, y1)放入vector中
代碼:
-
vector<Vec4i> lines;
-
HoughLinesP(result, lines, 1, PI/180, 50, 50, 120);
-
for(size_t i = 0; i < lines.size(); i++)
-
{
-
Vec4i l = lines[i];
-
line(image, Point(l[0], l[1]), Point(l[2],l[3]),Scalar(255), 3, CV_AA);
-
}
結果:
二:Hough變換檢測圓
事實上,任何可以用參數方程表示的幾何體都可嘗試用hough變換進行檢測。檢測圓整合了canny檢測和hough變換。
注意在hough圓變換前對圖像進行平滑,這樣可以減少可能引起誤檢測的圖像噪點。
代碼:
-
GaussianBlur(image, result, Size(5, 5), 1.5);
-
vector<Vec3f> circles;
-
HoughCircles(result, circles, CV_HOUGH_GRADIENT,
-
2,
-
50,
-
200,
-
100,
-
25, 100);
-
for(vector<Vec3f>::const_iterator itc = circles.begin(); itc != circles.end(); ++itc)
-
{
-
circle(image, Point((*itc)[0], (*itc)[1]), (*itc)[2], Scalar(255), 2);
-
}
結果: