目录
- 源码
- 效果
平台: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;
}