【机器视觉学习笔记】Hough变换直线检测(C++)
生活随笔
收集整理的這篇文章主要介紹了
【机器视觉学习笔记】Hough变换直线检测(C++)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
目錄
- 源碼
- 效果
平臺:Windows 10 20H2
Visual Studio 2015
OpenCV 4.5.3
本文源碼摘自OpenCV2馬拉松第22圈——Hough變換直線檢測原理與實現
源碼
#include <opencv2\opencv.hpp> #include <iostream> #include <opencv2\imgproc\types_c.h> #include<opencv2\imgproc\imgproc_c.h>using namespace cv; using namespace std;const double pi = 3.14159265358979f; const double RADIAN = 180.0 / pi;struct line {int theta;int r; };/* * r = xcos(theta) + ysin(theta) */ vector<struct line> houghLine(Mat &img, int threshold) {vector<struct line> lines;int diagonal = floor(sqrt(img.rows*img.rows + img.cols*img.cols));vector< vector<int> >p(360, vector<int>(diagonal));for (int j = 0; j < img.rows; j++) {for (int i = 0; i < img.cols; i++) {if (img.at<unsigned char>(j, i) > 0){for (int theta = 0; theta < 360; theta++){int r = floor(i*cos(theta / RADIAN) + j*sin(theta / RADIAN));if (r < 0)continue;p[theta][r]++;}}}}//get local maximumfor (int theta = 0; theta < 360; theta++){for (int r = 0; r < diagonal; r++){int thetaLeft = max(0, theta - 1);int thetaRight = min(359, theta + 1);int rLeft = max(0, r - 1);int rRight = min(diagonal - 1, r + 1);int tmp = p[theta][r];if (tmp > threshold&& tmp > p[thetaLeft][rLeft] && tmp > p[thetaLeft][r] && tmp > p[thetaLeft][rRight]&& tmp > p[theta][rLeft] && tmp > p[theta][rRight]&& tmp > p[thetaRight][rLeft] && tmp > p[thetaRight][r] && tmp > p[thetaRight][rRight]){struct line newline;newline.theta = theta;newline.r = r;lines.push_back(newline);}}}return lines; }void drawLines(Mat &img, const vector<struct line> &lines) {for (int i = 0; i < lines.size(); i++){vector<Point> points;int theta = lines[i].theta;int r = lines[i].r;double ct = cos(theta / RADIAN);double st = sin(theta / RADIAN);//r = x*ct + y*st//leftint y = int(r / st);if (y >= 0 && y < img.rows) {Point p(0, y);points.push_back(p);}//righty = int((r - ct*(img.cols - 1)) / st);if (y >= 0 && y < img.rows) {Point p(img.cols - 1, y);points.push_back(p);}//topint x = int(r / ct);if (x >= 0 && x < img.cols) {Point p(x, 0);points.push_back(p);}//downx = int((r - st*(img.rows - 1)) / ct);if (x >= 0 && x < img.cols) {Point p(x, img.rows - 1);points.push_back(p);}cv::line(img, points[0], points[1], Scalar(0, 0, 255), 1, CV_AA);} }//———————————————— //版權聲明:本文為CSDN博主「abcd1992719g」的原創文章,遵循CC 4.0 BY - SA版權協議,轉載請附上原文出處鏈接及本聲明。 //原文鏈接:https ://blog.csdn.net/abcd1992719g/article/details/27220445int main(int argc, char * argv[]) {Mat src, src_gray, edge;src = imread("D:\\Work\\OpenCV\\Workplace\\Test_1\\2.jpg");imshow("原圖", src);cvtColor(src, src_gray, CV_BGR2GRAY);Canny(src_gray, edge, 50, 200);vector<struct line> lines = houghLine(edge, 60);drawLines(src, lines);imshow("輸出", src);waitKey(0);return 0; }效果
總結
以上是生活随笔為你收集整理的【机器视觉学习笔记】Hough变换直线检测(C++)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Python操作Excel——win32
- 下一篇: 被圈粉的微信小程序纯UI组件colorU