RANSAC算法与原理(一)

article/2025/9/12 20:31:43

目录

      • 算法介绍
        • 举例
      • 算法的基本思想和流程
        • 算法的实现流程:
        • 迭代次数的推导
        • 算法的实现
      • python代码实现
      • References

算法介绍

首先我们从Random sample consensus - Wikipedia上找到RANSAC原理的介绍。

RANSAC算法的中文名称是随机抽样一致算法(Random Sample Consenus),简单的说,通过RANSAC算法,我们将数据分为inliersoutliers,inliers是对于模型拟合有效的点,也称之为内点outliers是对于模型拟合无效的点,也就是错误的数据点,称之为外点。而我们在使用观测数据拟合模型的过程中,外点的存在对于使用数据拟合模型是有害的,那么我们该如何剔除这些外点呢?RANSAC算法就是能够剔除外点的一个迭代性的算法。

举例

下图所示就是RANSAC算法的作用:剔除外点,使模型估计更加准确,参考Robust line model estimation using RANSAC — skimage v0.19.2 docs (scikit-image.org)

屏幕截图 2022-05-24 092807

算法的基本思想和流程

算法的实现流程:

  1. 选择出估计模型的最小数据样本(对于二维和三维直线拟合来说,确定一条直线最少需要2个点;对于三维平面拟合来说,确定一个三维平面最少需要3个点)
  2. 使用这个最小的数据样本,算出拟合的模型。(也就是直线方程或者平面方程)
  3. 将所有的模型带入这个拟合的模型,计算出内点 的数量。(数据点和拟合的模型的误差在一定阈值范围内的数据点的数量)
  4. 比较当前模型和之前迭代的得到的最好的模型的内点数量(内点数量越多,模型越好),记录最大的内点数的模型参数和内点数量。
  5. 重复1-4步,直到达到迭代终止条件(例如达到最大迭代数、内点数量达到迭代终止条件)

迭代次数的推导

假设内点在数据中所占的比例为 t t t
t = n i n l i e r s n i n l i e r s + n o u t l i e r s t=\frac{n_{inliers}}{n_{inliers}+n_{outliers}} t=ninliers+noutliersninliers
如果我们每次迭代都需要 N N N个点,那么每次迭代至少有一个外点的概率是:
P 1 = 1 − t N P_{1}=1-t^N P1=1tN
那么我们如果迭代 k k k次,所有的 k k k次迭代都至少有一个外点的概率为 P 1 k P_{1}^{k} P1k,那么这 k k k次迭代,能够采样到正确的 N N N内点去计算模型的概率就是上述概率的补集。
P = 1 − P 1 k = 1 − ( 1 − t N ) k P=1-P_{1}^{k}=1-(1-t^{N})^{k} P=1P1k=1(1tN)k
通过上式,我们可以求得
k = l o g ( 1 − P ) l o g ( 1 − t N ) k=\frac{log(1-P)}{log(1-t^{N})} k=log(1tN)log(1P)
注意:内点的概率 t t t是一个先验值,如果我们一开始不知道这个先验值 t t t,可以采用自适应迭代的方法,用当前的内点的比值来当成 t t t来估算迭代的次数。然后通过不断迭代,内点的比值也逐渐增大,再用新的更大的内点比值去代替 t t t的值;对于 P P P来说,一般会取一个定值0.99,等式(4)可以看出,当 P P P不变时, t t t越大, k k k越小, t t t越小, k k k越大。

算法的实现

Given:data – A set of observations.model – A model to explain observed data points.n – Minimum number of data points required to estimate model parameters.k – Maximum number of iterations allowed in the algorithm.t – Threshold value to determine data points that are fit well by model.d – Number of close data points required to assert that a model fits well to data.Return:bestFit – model parameters which best fit the data (or null if no good model is found)iterations = 0
bestFit = null
bestErr = something really largewhile iterations < k domaybeInliers := n randomly selected values from datamaybeModel := model parameters fitted to maybeInliersalsoInliers := empty setfor every point in data not in maybeInliers doif point fits maybeModel with an error smaller than tadd point to alsoInliersend ifend forif the number of elements in alsoInliers is > d then// This implies that we may have found a good model// now test how good it is.betterModel := model parameters fitted to all points in maybeInliers and alsoInliersthisErr := a measure of how well betterModel fits these pointsif thisErr < bestErr thenbestFit := betterModelbestErr := thisErrend ifend ifincrement iterations
end whilereturn bestFit

python代码实现

以下代码参考scikit-image/fit.py at v0.19.2 · scikit-image/scikit-image (github.com),也就是skimage的源码。

def _dynamic_max_trials(n_inliers, n_samples, min_samples, probability):if n_inliers == 0:return np.infif probability == 1:return np.infif n_inliers == n_samples:return 1nom = math.log(1 - probability)denom = math.log(1 - (n_inliers / n_samples) ** min_samples)return int(np.ceil(nom / denom))def ransac(data, model_class, min_samples, residual_threshold,is_data_valid=None, is_model_valid=None,max_trials=100, stop_sample_num=np.inf, stop_residuals_sum=0,stop_probability=1, random_state=None, initial_inliers=None):best_inlier_num = 0best_inlier_residuals_sum = np.infbest_inliers = []validate_model = is_model_valid is not Nonevalidate_data = is_data_valid is not Nonerandom_state = np.random.default_rng(random_state)# in case data is not pair of input and output, male it like itif not isinstance(data, (tuple, list)):data = (data, )num_samples = len(data[0])if not (0 < min_samples < num_samples):raise ValueError(f"`min_samples` must be in range (0, {num_samples})")if residual_threshold < 0:raise ValueError("`residual_threshold` must be greater than zero")if max_trials < 0:raise ValueError("`max_trials` must be greater than zero")if not (0 <= stop_probability <= 1):raise ValueError("`stop_probability` must be in range [0, 1]")if initial_inliers is not None and len(initial_inliers) != num_samples:raise ValueError(f"RANSAC received a vector of initial inliers (length "f"{len(initial_inliers)}) that didn't match the number of "f"samples ({num_samples}). The vector of initial inliers should "f"have the same length as the number of samples and contain only "f"True (this sample is an initial inlier) and False (this one "f"isn't) values.")# for the first run use initial guess of inliersspl_idxs = (initial_inliers if initial_inliers is not Noneelse random_state.choice(num_samples, min_samples,replace=False))# estimate model for current random sample setmodel = model_class()for num_trials in range(max_trials):# do sample selection according data pairssamples = [d[spl_idxs] for d in data]# for next iteration choose random sample set and be sure that# no samples repeatspl_idxs = random_state.choice(num_samples, min_samples, replace=False)# optional check if random sample set is validif validate_data and not is_data_valid(*samples):continuesuccess = model.estimate(*samples)# backwards compatibilityif success is not None and not success:continue# optional check if estimated model is validif validate_model and not is_model_valid(model, *samples):continueresiduals = np.abs(model.residuals(*data))# consensus set / inliersinliers = residuals < residual_thresholdresiduals_sum = residuals.dot(residuals)# choose as new best model if number of inliers is maximalinliers_count = np.count_nonzero(inliers)if (# more inliersinliers_count > best_inlier_num# same number of inliers but less "error" in terms of residualsor (inliers_count == best_inlier_numand residuals_sum < best_inlier_residuals_sum)):best_inlier_num = inliers_countbest_inlier_residuals_sum = residuals_sumbest_inliers = inliersdynamic_max_trials = _dynamic_max_trials(best_inlier_num,num_samples,min_samples,stop_probability)if (best_inlier_num >= stop_sample_numor best_inlier_residuals_sum <= stop_residuals_sumor num_trials >= dynamic_max_trials):break# estimate final model using all inliersif any(best_inliers):# select inliers for each data arraydata_inliers = [d[best_inliers] for d in data]model.estimate(*data_inliers)if validate_model and not is_model_valid(model, *data_inliers):warn("Estimated model is not valid. Try increasing max_trials.")else:model = Nonebest_inliers = Nonewarn("No inliers found. Model not fitted")return model, best_inliers

下一篇我们将重点讲解使用RANSAC拟合直线的例子,请移步RANSAC算法与原理(二)

References

Random sample consensus - Wikipedia

RANSAC算法详解(附Python拟合直线模型代码) - 知乎 (zhihu.com)

Robust line model estimation using RANSAC — skimage v0.19.2 docs (scikit-image.org)

scikit-image/fit.py at v0.19.2 · scikit-image/scikit-image (github.com)


http://chatgpt.dhexx.cn/article/bBU8CGm4.shtml

相关文章

RANSAC算法——看完保证你理解

目录 1 最小二乘算法的缺陷2 RANSAC算法2.1 原理2.2 实例2.3 参数 参考感谢阅读 RANSAC全程Random sample consensus&#xff0c;中文即“随机抽样一致算法”&#xff0c;该方法采用迭代的方式从一组包含离群&#xff08;outlier或者错误数据&#xff09;的被观测数据中估算出数…

RANSAC算法介绍

一、RANSAC介绍 随机抽样一致算法&#xff08;RANdom SAmple Consensus,RANSAC&#xff09;,采用迭代的方式从一组包含离群的被观测数据中估算出数学模型的参数。RANSAC算法假设数据中包含正确数据和异常数据&#xff08;或称为噪声&#xff09;。正确数据记为内点&#xff08;…

RANSAC算法讲解

RANSAC是“RANdom SAmple Consensus&#xff08;随机抽样一致&#xff09;”的缩写。它可以从一组包含“局外点”的观测数据集中&#xff0c;通过迭代方式估计数学模型的参数。它是一种不确定的算法——它有一定的概率得出一个合理的结果&#xff1b;为了提高概率必须提高迭代次…

RANSAC介绍(Matlab版直线拟合+平面拟合)

RANSAC介绍&#xff08;Matlab版直线拟合平面拟合&#xff09; 本人邮箱&#xff1a;sylvester0510163.com&#xff0c;欢迎交流讨论&#xff0c; 欢迎转载&#xff0c;转载请注明网址http://blog.csdn.net/u010128736/ 一、RANSAC介绍 随机抽样一致算法&#xff08;RANdom SA…

RANSAC算法(仅供学习使用)

1.定义 RANSAC&#xff08;Random Sample Consensus&#xff09;算法是一种基于随机采样的迭代算法&#xff0c;用于估计一个数学模型参数。它最初由Fischler和Bolles于1981年提出&#xff0c;主要用于计算机视觉和计算机图形学中的模型拟合和参数估计问题。 RANSAC算法的基本…

前端调试手机app

有时候应用在电脑网页端显示是正常的&#xff0c;但是一安装到手机上或者在手机浏览器上打开&#xff0c;就会显示各种问题问题。 在网上找了很长时间&#xff0c;最方便的就是利用在电脑上利用谷歌浏览器进行调试&#xff0c;输入网址chrome://inspect/#devices&#xff0c;进…

跨平台应用开发进阶(三十七)uni-app前端监控方案 Sentry 探究

文章目录 一、前言二、Sentry 简介三、Sentry 部署3.1 docker 的部署 (mac版)3.2 部署 sentry3.3 创建项目3.4 前端部署&#xff0c;注入监控代码 四、sentry 操作界面介绍五、拓展阅读 一、前言 在日益发达的网络时代&#xff0c;web应用也是越来越复杂&#xff0c;尤其是前端…

uni-app 开发跨平台应用前端框架

前言 uni-app 是一个使用 vue.js 开发跨平台应用的前端框架&#xff0c;由于它具备"编写一次代码可发布到多个平台"的特点&#xff0c;大大的节省了开发成本&#xff0c;极速提升了开发效率。 一、uni-app 简介 uni-app 是一个使用 Vue.js 开发所有前端应用的框架。…

uni-app开发所有前端应用的框架

uni-app 是一个使用 Vue.js 开发所有前端应用的框架&#xff0c;开发者编写一套代码&#xff0c;可发布到iOS、Android、H5、以及各种小程序&#xff08;微信/支付宝/百度/头条/QQ/钉钉&#xff09;等多个平台。 DCloud公司拥有420万开发者&#xff0c;几十万应用案例、6.5亿手…

比较几种热门Hybrid App前端框架

作为一种既能够在原生应用程序环境中运行&#xff0c;也能够在 Web 浏览器中运行的应用程序&#xff0c;Hybrid App 主要使用 Web 技术进行开发&#xff0c;如 HTML、CSS 和JavaScript&#xff0c;并使用一个中间层将其封装在原生应用程序中。随着技术的持续推进&#xff0c;Hy…

APP管理平台--前端篇,首页(三)

作为首页&#xff0c;肯定在打开网址后就看得到对应信息。那么作为APP管理平台&#xff0c;这个信息自然而然的表现成了APP列表。那么依据现有各大应用市场需要分为已上线和未上线。但是在实际做的时候没有区分&#xff0c;这次项目中将所有新增的APP都展示了。区分布局就决定了…

一天撸一个财务APP系统【安卓端+前端+后端】

昨天有个粉丝朋友也想学开发Web和小程序、安卓&#xff0c;问可以在大学学会吗&#xff1f; 在学校学到的东西真的有限&#xff1a; 在很多的高校&#xff0c;有一些教授是学院派的&#xff0c;他们没有做过多少开发工作&#xff0c;上课就是照本宣科&#xff0c;讲的知识点都…

如何查看手机APP使用的前端框架?

一、首先获取该APP的apk包&#xff08;长按APP&#xff0c;点击‘分享’&#xff0c;分享到微信‘文件传输助手’&#xff0c;即可获得apk包--参考本博主上篇文章&#xff09;。 二、把apk扩展名改成.zip然后解压。不同的编译软件目录结果也不一样。&#xff08;为方便起见&am…

【网络协议】IPV4协议介绍

&#x1f4aa;本节内容&#xff1a;IPV4协议介绍、IPV4地址格式、IPV4数据格式及C项目结构体设计 &#x1f60f;【Qt6网络抓包工具项目实战】总导航目录&#xff08;建议收藏书签~~~&#xff09; ✌️ part1 &#x1f60f;【Qt6网络抓包工具项目实战】1.1Qt6.2.2环境搭建(免费…

DHCP协议

目录 1、DHCP协议 2、DHCP的工作过程 动态获取IP地址流程 跟新租期流程 解除租期流程 1、DHCP协议 DHCP(Dynamic Host Configuration Protocol)协议是处于应用层的协议。一个主机如果想正常上网&#xff0c;需要配置IP地址&#xff0c;子网掩码&#xff0c;默认网关基本配置…

TCP/IP-----协议号、端口号、ARP、icmp

文章目录 一、数据流向过程二、协议详解1&#xff09;ARP协议2&#xff09;ICMP协议 协议号 协议号是存在于IP数据报的首部的20字节的固定部分&#xff0c;占有8bit.该字段是指出此数据报所携带的是数据是使用何种协议&#xff0c;以便目的主机的IP层知道将数据部分上交给哪个处…

UDP协议

引言 本文中只关于IPv4&#xff1b;UDP是一种保留消息边界的简单的面向数据报的传输层协议。它不提供差错纠正、队列管理、重复消除、流量控制和拥塞控制。总之&#xff0c;能没有的都没了。但它提供了差错检测&#xff0c;是一种端到端的校验和。因此使用它的程序必须自己实现…

BGP协议

BGP协议 工作层工作原理BGP简单配置———含密码认证配置个人图解BGP 工作层 BGP是工作在应用层的协议&#xff0c;但基于传输层的TCP协议 工作原理 路由协议通常分为内部网关协议&#xff08;IGP: Interior Gateway Protocol&#xff09;和外部网关协议&#xff08;EGP: Ext…

IP协议介绍

文章目录 定义特点作用寻址和路由&#xff1a;分片与重组&#xff1a; ①TCP分段与IP分片的区别&#xff1f;TCP分段IP分片什么是MSS&#xff1f;滑动窗口与MSS的区别&#xff1f; 什么是MTU&#xff1f;MSS与MTU的关系疑问UDP是否会进行分段&#xff1f;TCP分段后会进行IP分片…

华为 协议归纳总结

青出于蓝而胜于蓝 文章目录 一、路由优先级二、路由协议三、常见的永久组地址四、常用的UDP协议及端口号五、常用的TCP协议及端口号六、协议七、报文头格式 一些常用的知识点&#xff0c;经常用到&#xff0c;也很容易忘记、混淆&#xff0c;所以有必要去整理一下这些常用知识点…