当前位置: 首页 > news >正文

直线拟合例子 ,岭回归拟合直线

目录

直线拟合,算出离群点

岭回归拟合直线:


直线拟合,算出离群点

import cv2
import numpy as np# 输入的点
points = np.array([[51, 149],[122, 374],[225, 376],[340, 382],[463, 391],[535, 298],[596, 400],[689, 406],[821, 407]
], dtype=np.float32)# 使用 RANSAC 算法拟合直线,并返回内点和离群点
def fit_line_ransac(points, max_iters=1000, threshold=10):"""使用 RANSAC 算法拟合直线,并判断离群点:param points: 输入的点集,形状为 (N, 2):param max_iters: 最大迭代次数:param threshold: 内点阈值:return: 拟合直线的斜率和截距 (k, b), 内点索引, 离群点索引"""best_k, best_b = 0, 0best_inliers = []max_inliers = 0for _ in range(max_iters):# 随机选择两个点sample_indices = np.random.choice(len(points), 2, replace=False)sample = points[sample_indices]x1, y1 = sample[0]x2, y2 = sample[1]# 计算直线的斜率和截距if x1 == x2:  # 垂直线k = float('inf')b = x1else:k = (y2 - y1) / (x2 - x1)b = y1 - k * x1# 计算所有点到直线的距离distances = np.abs(k * points[:, 0] - points[:, 1] + b) / np.sqrt(k**2 + 1)# 统计内点inliers = np.where(distances < threshold)[0]# 更新最佳模型if len(inliers) > max_inliers:max_inliers = len(inliers)best_k, best_b = k, bbest_inliers = inliers# 离群点 = 所有点 - 内点outliers = np.setdiff1d(np.arange(len(points)), best_inliers)return (best_k, best_b), best_inliers, outliers# 使用 OpenCV 绘制点、拟合直线和内点/离群点
def draw_points_and_line(image, points, inliers, outliers, k, b, color_line=(255, 0, 0), color_inliers=(0, 255, 0), color_outliers=(0, 0, 255)):"""使用 OpenCV 绘制点、拟合直线和内点/离群点:param image: 背景图像:param points: 输入的点集:param inliers: 内点索引:param outliers: 离群点索引:param k: 直线斜率:param b: 直线截距:param color_line: 直线颜色 (BGR):param color_inliers: 内点颜色 (BGR):param color_outliers: 离群点颜色 (BGR)"""# 绘制内点for i in inliers:x, y = points[i]cv2.circle(image, (int(x), int(y)), 5, color_inliers, -1)# 绘制离群点for i in outliers:x, y = points[i]cv2.circle(image, (int(x), int(y)), 5, color_outliers, -1)# 绘制拟合直线x_min, x_max = int(np.min(points[:, 0])), int(np.max(points[:, 0]))y_min = int(k * x_min + b)y_max = int(k * x_max + b)cv2.line(image, (x_min, y_min), (x_max, y_max), color_line, 2)# 创建背景图像
image_width = 1000  # 图像宽度
image_height = 600  # 图像高度
background = np.zeros((image_height, image_width, 3), dtype=np.uint8)  # 黑色背景# 使用 RANSAC 算法拟合直线,并判断离群点
(k, b), inliers, outliers = fit_line_ransac(points)
print(f"RANSAC 拟合直线: y = {k:.2f}x + {b:.2f}")
print(f"内点索引: {inliers}")
print(f"离群点索引: {outliers}")# 绘制点、拟合直线和内点/离群点
draw_points_and_line(background, points, inliers, outliers, k, b)# 显示图像
cv2.imshow("RANSAC Line Fitting with OpenCV", background)
cv2.waitKey(0)
cv2.destroyAllWindows()# 保存图像
cv2.imwrite("ransac_line_fitting_opencv.jpg", background)

岭回归拟合直线:

import cv2
import numpy as np
from sklearn.linear_model import Ridge# 生成带噪声的点
np.random.seed(42)
num_points = 100
x = np.linspace(0, 10, num_points)
y = 2 * x + 1 + np.random.normal(0, 1, num_points)  # y = 2x + 1 + 噪声# 将 x 转换为二维数组(因为 sklearn 需要二维输入)
X = x.reshape(-1, 1)# 使用岭回归拟合直线
ridge = Ridge(alpha=1.0)  # alpha 是正则化强度
ridge.fit(X, y)# 获取拟合的斜率和截距
slope = ridge.coef_[0]
intercept = ridge.intercept_# 打印拟合结果
print(f"拟合直线方程: y = {slope:.2f}x + {intercept:.2f}")# 计算拟合直线的两个端点
x_min, x_max = 0, 10
y_min = slope * x_min + intercept
y_max = slope * x_max + intercept# 将点缩放到图像尺寸
scale = 40  # 缩放因子
image_width = 640
image_height = 480# 创建一个空白图像用于可视化
image = np.zeros((image_height, image_width, 3), dtype=np.uint8)# 绘制点
for xi, yi in zip(x, y):cv2.circle(image, (int(xi * scale), int(yi * scale)), 3, (0, 255, 0), -1)# 绘制拟合的直线
pt1 = (int(x_min * scale), int(y_min * scale))
pt2 = (int(x_max * scale), int(y_max * scale))
cv2.line(image, pt1, pt2, (0, 0, 255), 2)# 显示图像
cv2.imshow("Ridge Regression Line Fit", image)
cv2.waitKey(0)
cv2.destroyAllWindows()

http://www.lryc.cn/news/526127.html

相关文章:

  • Flutter android debug 编译报错问题。插件编译报错
  • 关于IPD流程的学习理解和使用
  • C# 类(Class)
  • Jenkins pipline怎么设置定时跑脚本
  • PostgreSQL模糊查询相关学习参考
  • 【电脑无法通过鼠标和键盘唤醒应该怎么办】
  • Java 大视界 -- Java 大数据中的数据脱敏技术与合规实践(60)
  • Vue3.5 企业级管理系统实战(三):页面布局及样式处理 (Scss UnoCSS )
  • 【xcode 16.2】升级xcode后mac端flutter版的sentry报错
  • windows在命令行中切换盘符
  • 亚博microros小车-原生ubuntu支持系列:11手指控制与手势识别
  • JAVA-快速排序
  • 日志收集Day003
  • 基于quartz,刷新定时器的cron表达式
  • 数学大模型MAmmoTH:通过混合说明调整建立数学通才模型
  • Opencv学习
  • python生成图片和pdf,快速
  • 剑指Offer|LCR 044.在每个树行中找最大值
  • PWM信号概述
  • 关于BAR(PCIE BAR或AXI BAR)的解释
  • 计算机的错误计算(二百二十一)
  • 【力扣Hot 100】矩阵1
  • 移动端VR处理器和传统显卡的不同
  • 「 机器人 」利用数据驱动模型替代仿真器:加速策略训练并降低硬件依赖
  • MATLAB 如何避免复杂shp文件对inpolygon的影响
  • 【2024年华为OD机试】 (C卷,200分)- 贪吃的猴子(JavaScriptJava PythonC/C++)
  • PostgreSQL中级专家是什么意思?
  • 从根源分析,调试,定位和解决MacOS ld: unsupported tapi file type ‘!tapi-tbd‘ in YAML file
  • 【Uniapp-Vue3】previewImage图片预览
  • doris:Insert Into Values