OpenCV图像处理——直线拟合并找出拟合直线的起点与端点

引言

对轮廓进行分析,除了可以对轮廓进行椭圆或者圆的拟合之外,还可以对轮廓点集进行直线拟合。在 OpenCV 中,直线拟合通常是通过 cv::fitLine 函数实现的,该函数采用最小二乘法对一组 2D 或 3D 点进行直线拟合。对于 2D 点集,拟合结果是一个 cv::Vec4f 类型的向量,包含了直线的方向向量和直线上的一个点。这个方向向量可以被转换为直线的斜率和截距,从而得到直线的方程。

OpenCV实现直线拟合的API如下:

void cv::fitLine(
	InputArray points,
	OutputArray line,
	int distType,
	double param,
	double reps,
	double aeps 
)
points表示待拟合的输入点集合
line在二维拟合时候输出的是vec4f类型的数据,在三维拟合的时候输出是vec6f的vector
distType表示在拟合时候使用距离计算公式是哪一种,OpenCV支持如下六种方式:
    DIST_L1 = 1
    DIST_L2 = 2
    DIST_L12 = 4
    DIST_FAIR = 5
    DIST_WELSCH = 6
    DIST_HUBER = 7
param对模型拟合距离计算公式需要参数C,5~7 distType需要参数C
reps与aeps是指对拟合结果的精度要求,一般取0.01

在这里插入图片描述

示例代码

void fit_line_points(std::vector<cv::Point>& points, cv::Point2f& p1, cv::Point2f& p2)
{
	// 使用 fitLine 拟合直线
	cv::Vec4f line;
	fitLine(points, line, cv::DIST_L2, 0, 0.01, 0.01);

	cv::Point2f pointOnLine(line[2], line[3]); // 直线上的一个点
	cv::Point2f direction(line[0], line[1]);   // 直线的方向向量

	// 找到拟合直线方向上投影距离最小和最大的点(计算端点)
	float t_min = FLT_MAX, t_max = -FLT_MAX;
	cv::Point2f minPoint, maxPoint;

	for (const auto& pt : points) {
		// 投影长度 t = (pt - pointOnLine) · direction
		float t = (pt.x - pointOnLine.x) * direction.x + (pt.y - pointOnLine.y) * direction.y;
		if (t < t_min) {
			t_min = t;
			minPoint = pt;
		}
		if (t > t_max) {
			t_max = t;
			maxPoint = pt;
		}
	}

	// 使用方向向量扩展点,计算直线的两个顶点
	p1 = pointOnLine + direction * t_min;
	p2 = pointOnLine + direction * t_max;
}

调用函数:

int main() 
{
    // 创建一些示例点
    vector<Point2f> points = {
        Point2f(100, 100), Point2f(150, 200), Point2f(200, 300),
        Point2f(300, 400), Point2f(400, 500), Point2f(500, 600)
    };

    // 拟合直线并找到直线的两个顶点
    LineEndpoints result = fitLineAndFindEndpoints(points);

    // 打印结果
    cout << "Endpoint 1: [" << result.endpoint1.x << ", " << result.endpoint1.y << "]" << endl;
    cout << "Endpoint 2: [" << result.endpoint2.x << ", " << result.endpoint2.y << "]" << endl;

    // 在图像上绘制这些点和拟合的直线
    Mat image = Mat::zeros(Size(800, 800), CV_8UC3);
    for (const auto& pt : points) {
        circle(image, pt, 5, Scalar(0, 0, 255), FILLED);
    }
    line(image, result.endpoint1, result.endpoint2, Scalar(0, 255, 0), 2);
    circle(image, result.endpoint1, 5, Scalar(255, 0, 0), FILLED);
    circle(image, result.endpoint2, 5, Scalar(255, 0, 0), FILLED);

    // 显示结果图像
    namedWindow("Fitted Line", WINDOW_AUTOSIZE);
    imshow("Fitted Line", image);
    waitKey(0);

    return 0;
}

实现结果:
在这里插入图片描述

代码说明

  1. 点集创建:

    • 首先创建了一组示例点,这些点可以是任意想要拟合的点集。
  2. 拟合直线:

    • cv::fitLine 函数用于对点集进行直线拟合。它返回一个包含直线参数的 Vec4f 向量:
      • line[0]line[1] 是直线的方向向量 (vx, vy)
      • line[2]line[3] 是直线上的一个点 (x0, y0)
  3. 计算最远的两个点:

    • 对于每个点,计算其在拟合直线上的投影长度 t。投影长度 t 计算方式是点到直线上某一点的向量与方向向量的点积。
    • 通过比较 t 值,找到投影最小的点 minPoint 和投影最大的点 maxPoint。这两个点就是距离最远的点。
  4. 绘制直线与最远的点:

    • 使用 line 函数在图像上绘制拟合的直线(连接 minPointmaxPoint)。
    • 使用 circle 函数标记最远的两个点。
  5. 显示结果:

    • 使用 imshow 函数显示结果图像,其中红色点表示原始点集,绿色直线是拟合的直线,蓝色点是距离最远的两个点。
在Python和OpenCV中实现直线检测,可以使用Hough变换来检测直线。Hough变换是一种常用的图像处理方法,可用于检测直线、圆等几何形状。 以下是一个简单的示例代码,使用Hough变换来检测直线并计算交点: ```python import cv2 import numpy as np # 读取图像 img = cv2.imread('test.jpg') gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # 边缘检测 edges = cv2.Canny(gray, 50, 150, apertureSize=3) # Hough变换检测直线 lines = cv2.HoughLines(edges, 1, np.pi/180, 200) # 计算交点 points = [] for i in range(len(lines)): for j in range(i+1, len(lines)): rho1, theta1 = lines[i][0] rho2, theta2 = lines[j][0] if abs(theta1 - theta2) < np.pi/4: continue a = np.array([[np.cos(theta1), np.sin(theta1)], [np.cos(theta2), np.sin(theta2)]]) b = np.array([rho1, rho2]) x0, y0 = np.linalg.solve(a, b) points.append((int(x0), int(y0))) # 绘制直线和交点 for line in lines: rho, theta = line[0] a = np.cos(theta) b = np.sin(theta) x0 = a*rho y0 = b*rho x1 = int(x0 + 1000*(-b)) y1 = int(y0 + 1000*(a)) x2 = int(x0 - 1000*(-b)) y2 = int(y0 - 1000*(a)) cv2.line(img, (x1,y1), (x2,y2), (0,0,255), 2) for point in points: cv2.circle(img, point, 5, (0,255,0), -1) # 显示图像 cv2.imshow('image', img) cv2.waitKey(0) cv2.destroyAllWindows() ``` 在代码中,首先读取图像并进行灰度转换和边缘检测。然后使用Hough变换检测直线,并计算交点。最后绘制直线和交点,并显示图像。 需要注意的是,在计算交点时,需要将两条直线的极坐标表示转换为直角坐标表示,并使用线性方程组求解。 希望这个例子能够帮助到你实现直线检测并计算交点。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

知来者逆

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值