C++ opencv直线检测
时间: 2023-06-28 09:13:23 浏览: 161
OpenCV 中提供了 Hough 变换来进行直线检测。下面是一个简单的示例代码:
```cpp
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace cv;
using namespace std;
int main()
{
Mat src = imread("test.jpg");
if (src.empty())
{
cout << "Failed to read image" << endl;
return -1;
}
Mat gray, edges;
cvtColor(src, gray, COLOR_BGR2GRAY);
Canny(gray, edges, 50, 200, 3);
vector<Vec2f> lines;
HoughLines(edges, lines, 1, CV_PI / 180, 150, 0, 0);
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(src, pt1, pt2, Scalar(0, 0, 255), 2, LINE_AA);
}
imshow("Result", src);
waitKey(0);
return 0;
}
```
该示例代码从文件中读取一张图像,然后将其转换为灰度图像和边缘图像。接着,使用 Hough 变换检测直线,并在原始图像上绘制检测到的直线。最后将结果显示出来。
阅读全文