Python-Opencv fitLine 拟合直线

本文详细介绍了使用OpenCV库中的fitLine函数进行直线拟合的过程。解释了不同距离类型参数对拟合结果的影响,包括欧式距离、L1、L2等,并提供了计算斜率和截距的具体步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

转自:

output = cv2.fitLine(InputArray points, distType, param, reps, aeps)
参数:
InputArray Points: 待拟合的直线的集合,必须是矩阵形式(如numpy.array)
distType: 距离类型。fitline为距离最小化函数,拟合直线时,要使输入点到拟合直线的距离和最小化。这里的距离的类型有以下几种:
cv2.DIST_USER : User defined distance
cv2.DIST_L1: distance = |x1-x2| + |y1-y2|
cv2.DIST_L2: 欧式距离,此时与最小二乘法相同
cv2.DIST_C: distance = max(|x1-x2|,|y1-y2|)
cv2.DIST_L12: L1-L2 metric: distance = 2(sqrt(1+x*x/2) - 1))
cv2.DIST_FAIR
cv2.DIST_WELSCH
cv2.DIST_HUBER
param: 距离参数,跟所选的距离类型有关,值可以设置为0
reps,aeps: 第5/6个参数用于表示拟合直线所需要的径向和角度精度,通常情况下两个值均被设定为0.01

output:对于二维直线,输出output为4维,前两维代表拟合出的直线的方向,后两位代表直线上的一点
拟合后直线点的斜率k和偏移b

loc = np.array(loc)
output = cv2.fitLine(loc, cv2.DIST_L2, 0, 0.01, 0.01)
k = output[1] / output[0]
b = output[3] - k * output[2]
### 使用 PythonOpenCV 实现点的直线拟合 #### 方法一:利用 `cv.fitLine` 函数进行最小二乘法拟合OpenCV 中,可以使用 `cv.fitLine` 函数来执行最小二乘法拟合直线的操作。此函数能够处理二维和三维点集,并返回描述最佳拟合直线的相关参数。 ```python import numpy as np import cv2 from matplotlib import pyplot as plt # 创建一些测试数据点 points = np.array([[1, 2], [2, 3], [3, 8], [4, 7]], dtype=np.float32) # 应用 fitLine 进行直线拟合 [vx, vy, x0, y0] = cv2.fitLine(points, cv2.DIST_L2, 0, 0.01, 0.01)[^2] # 计算用于绘图的一系列坐标点 lefty = int((-x0 * vy / vx) + y0) righty = int(((1000 - x0) * vy / vx) + y0) plt.scatter(points[:, 0], points[:, 1]) plt.plot([x0, 1000], [y0, righty], color='red') plt.xlim(0, 10) plt.ylim(0, 10) plt.gca().invert_yaxis() # 反转Y轴以便于图像显示正常 plt.show() ``` 这段代码创建了一个简单的散点图并展示了通过这些点拟合出来的红色线条。 #### 方法二:采用 RANSAC 随机抽样一致性算法 另一种常用的方法是应用 RANSAC(Random Sample Consensus),它特别适合含有异常值的数据集。这种方法可以在存在噪声的情况下更稳健地找到模型参数。 ```python def ransac_line_fitting(data_points, n_iterations=100, threshold_distance=1): best_model = None max_inliers_count = 0 for _ in range(n_iterations): sample_indices = np.random.choice(len(data_points), size=2, replace=False) point_1, point_2 = data_points[sample_indices] A = np.vstack([point_1, point_2]).T B = np.ones((2,)) m, c = np.linalg.lstsq(A, B, rcond=None)[0][:2] distances = abs(m * data_points[:, 0] - data_points[:, 1] + c) / ((m ** 2 + 1) ** .5) inlier_mask = distances < threshold_distance current_inliers_count = sum(inlier_mask) if current_inliers_count > max_inliers_count: max_inliers_count = current_inliers_count best_model = (m, c) return best_model data_points = np.array([[1, 2], [2, 3], [3, 8], [4, 7]]) model_parameters = ransac_line_fitting(data_points) print(f"The fitted line equation is: y={model_parameters[0]}*x+{model_parameters[1]}") ``` 上述例子实现了基本版本的 RANSAC 算法来进行直线拟合操作[^4]。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值