opencv拟图片中所有直线的代码c++
时间: 2023-12-31 18:05:48 浏览: 29
以下是使用OpenCV C++实现的代码,用于检测图像中的所有直线:
```c++
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace cv;
using namespace std;
int main()
{
Mat img = imread("image.jpg", IMREAD_GRAYSCALE);
if (img.empty())
{
cout << "Could not read the image" << endl;
return 1;
}
Mat edges;
Canny(img, edges, 50, 200, 3);
vector<Vec2f> lines;
HoughLines(edges, lines, 1, CV_PI/180, 100);
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(img, pt1, pt2, Scalar(0,0,255), 3, LINE_AA);
}
imshow("Detected Lines", img);
waitKey();
return 0;
}
```
这个代码使用Canny算子检测边缘,然后通过霍夫变换检测直线。在检测到直线后,将直线绘制在原始图像上。