使用matlab进行RANSAC直线检测

在一堆随机点中隐藏一条直线,通过RANSAC方法检测出来。

clear
close all
clc

%% 生成30个随机点,然后添加11个点的直线,打乱点的顺序
Points = rand(30,2);
line = 0:0.1:1;
y = 0.5 * line + 0.1 + (rand(1,11)-0.5)/50;

Points = [Points; cat(1, line, y)'];
scatter(Points(:,1), Points(:,2), 10, 'k', 'filled');
hold on
grid on
daspect([1 1 1]);

Points(:,3) = rand(size(Points,1), 1);
Points = sortrows(Points, 3);

X = Points(:, 1);
Y = Points(:, 2);

%% 尝试1000次
n = 1000;
tol = 0.01;
for i = 1 : n
    choose = randperm(length(X));
    choose = choose(1:5);
    choose_x = X(choose);
    choose_y = Y(choose);
    
    t = polyfit(choose_x, choose_y, 1);
    all_distance = abs(t(1)*X-Y+t(2))/sqrt(t(1)^2+(-1)^2);
    choose = all_distance < tol;
    choose_x = X(choose);
    choose_y = Y(choose);
    
    t = polyfit(choose_x, choose_y, 1);
    distance = abs(t(1)*choose_x-choose_y+t(2))/sqrt(t(1)^2+(-1)^2);
    final_t(i,:) = t;
    final_choose_num(i) = sum(choose);
    final_choose_point{i} = choose;
    final_distance(i) = mean(distance);
end

%% 给模型打分,点数越多,误差越小,得分越高
% score = -final_distance .* final_choose_num + final_choose_num;
score = final_choose_num;
[m,index] = max(score);
t = final_t(index,:);
choose = final_choose_point{index};
choose_x = X(choose);
choose_y = Y(choose);
% figure;
% scatter(Points(:,1), Points(:,2), 10, 'k', 'filled');
hold on
plot(choose_x, choose_y, 'b*', choose_x, polyval(t,choose_x), 'r-');
legend('所有点', '内点', '最终拟合直线')
hold on
grid on
daspect([1 1 1]);

在这里插入图片描述

  • 0
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值