在一堆随机点中隐藏一条直线,通过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]);