opencv选定四点拟合两条直线计算交点
时间: 2023-10-30 14:09:22 浏览: 73
首先,使用OpenCV的`cv::fitLine`函数拟合两条直线。该函数接受一个包含所有点的数组,并返回一个向量和一个点(这两个参数定义了完整的直线)。对于每条直线,我们可以使用`cv::line`函数从左到右绘制直线上的两个点。
然后,我们可以通过解两条直线的方程来计算它们的交点。对于两条直线$Ax+By=C$和$Dx+Ey=F$,交点可以通过以下方式计算:
$x = \frac{BF-EC}{AD-BE}$
$y = \frac{CD-AF}{BE-AD}$
最后,我们可以使用`cv::circle`函数在交点处绘制一个小圆。
下面是示例代码:
```cpp
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace cv;
using namespace std;
int main()
{
// 读入图像
Mat img = imread("lines.png");
// 灰度化
Mat gray;
cvtColor(img, gray, COLOR_BGR2GRAY);
// 边缘检测
Mat edges;
Canny(gray, edges, 50, 150);
// Hough 直线检测
vector<Vec2f> lines;
HoughLines(edges, lines, 1, CV_PI/180, 50);
// 绘制直线
Mat line_img = img.clone();
Point pt1, pt2;
for (size_t i = 0; i < lines.size(); i++)
{
float rho = lines[i][0], theta = lines[i][1];
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(line_img, pt1, pt2, Scalar(0, 0, 255), 3, LINE_AA);
}
// 选取四个点
vector<Point2f> points;
points.push_back(Point2f(399, 330));
points.push_back(Point2f(607, 330));
points.push_back(Point2f(320, 474));
points.push_back(Point2f(696, 474));
// 拟合两条直线
Vec4f line1, line2;
fitLine(points.rowRange(0, 2), line1, DIST_L2, 0, 0.01, 0.01);
fitLine(points.rowRange(2, 4), line2, DIST_L2, 0, 0.01, 0.01);
// 计算交点
float x1 = line1[2], y1 = line1[3];
float x2 = x1 + line1[0], y2 = y1 + line1[1];
float x3 = line2[2], y3 = line2[3];
float x4 = x3 + line2[0], y4 = y3 + line2[1];
float a1 = y2 - y1, b1 = x1 - x2, c1 = x2*y1 - x1*y2;
float a2 = y4 - y3, b2 = x3 - x4, c2 = x4*y3 - x3*y4;
float x = (b2*c1 - b1*c2) / (a1*b2 - a2*b1);
float y = (a1*c2 - a2*c1) / (a1*b2 - a2*b1);
// 绘制交点
circle(line_img, Point(x, y), 5, Scalar(0, 255, 0), -1);
// 显示结果
imshow("Lines", line_img);
waitKey();
return 0;
}
```
这里使用的示例图像如下所示:
![lines](https://img-blog.csdn.net/20180313223956849?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvZGFuaWVsX3N1bW1lcl9zYXZl/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/q/75)