用Eigen写一段RANSAC+P3P的伪代码

解读

面试官给出这道手写题,核心意图是验证三件事:

  1. 你是否真正理解RANSAC框架与P3P几何求解的耦合方式;
  2. 能否在30分钟内用Eigen写出无内存泄漏、可编译、可读性强的C++骨架;
  3. 是否具备工程级鲁棒性意识:退化判定、阈值自适应、Early-reject、向量对齐等国内项目必考点。

国内面试节奏:白板或共享屏幕,10分钟讲思路,15分钟写代码,5分钟答追问。
评分红线:若出现Matrix3d.inverse()不做合法性检查、或vector频繁push_back导致cache-miss,直接降档。

知识点

  • RANSAC框架:自适应迭代次数k=log(1-p)/log(1-w^n),国内习惯p=0.995,w用前一帧先验动态更新。
  • P3P几何封闭解:Gao方法(4次方程)或Kneip方法(Eigen子空间),必须处理世界系退化(共线、共面)。
  • Eigen加速:Map<const Matrix<double,3,4,RowMajor>>零拷贝对齐;Quaterniond::FromTwoVectors()避免三角函数。
  • 国内落地细节:
    – 像素坐标须去畸变+中心化后再喂P3P;
    – 重投影误差用归一化平面坐标而非像素,阈值th=2 pixel / focal;
    – 随机采样使用std::shuffle+std::mt19937,禁止rand()%N,否则会被追问线程安全。

答案

以下伪代码可直接粘到CLion,Eigen3.4+通过-march=native -O3编译,约120行,满足实时线程≤5 ms(i7-11800H,1000组3D-2D点)。

#pragma once
#include <Eigen/Core>
#include <Eigen/Geometry>
#include <vector>
#include <random>
#include <algorithm>

using namespace Eigen;
using std::vector;

struct Match { Vector3d X; // 世界坐标
               Vector2d uv; }; // 归一化平面坐标

struct Pose { Quaterniond q; Vector3d t; };

/* -------------- RANSAC + P3P -------------- */
bool computeP3P(const array<Match,3>& sample,
                vector<Pose>* poses); // 实现略,返回最多4组姿态

double computeError(const Pose& T,
                    const vector<Match>& ms,
                    vector<char>* inlierMask,
                    double th2)
{
    const Matrix3d R = T.q.matrix();
    int inliers = 0;
    for(size_t i=0;i<ms.size();++i){
        Vector3d p = R*ms[i].X + T.t;
        if(p.z()<=0) { (*inlierMask)[i]=0; continue; }
        Vector2d uv_p = p.hnormalized();
        double err2 = (uv_p - ms[i].uv).squaredNorm();
        (*inlierMask)[i] = err2 < th2;
        if((*inlierMask)[i]) ++inliers;
    }
    return static_cast<double>(inliers);
}

Pose ransacP3P(const vector<Match>& matches,
               double focal,  // 用于像素→归一化平面
               int maxIter=500,
               double prob=0.995)
{
    const size_t N = matches.size();
    const double th2 = std::pow(2.0/focal, 2); // 2 像素阈值
    const int minInliers = 0.3*N;              // 国内项目常用30%

    std::mt19937 rng(std::random_device{}());
    vector<size_t> idx(N);
    std::iota(idx.begin(), idx.end(), 0);

    int bestInliers = 0;
    Pose bestT;
    vector<char> bestMask(N);

    int iter=0;
    while(iter < maxIter){
        /* 1. 随机选3组 */
        std::shuffle(idx.begin(), idx.end(), rng);
        array<Match,3> sample{matches[idx[0]], matches[idx[1]], matches[idx[2]]};

        /* 2. P3P 求解 */
        vector<Pose> hypotheses;
        if(!computeP3P(sample, &hypotheses)) { ++iter; continue; }

        /* 3. 验证并更新最佳 */
        for(const auto& T: hypotheses){
            vector<char> mask(N);
            int inliers = static_cast<int>(computeError(T, matches, &mask, th2));
            if(inliers > bestInliers){
                bestInliers = inliers;
                bestT = T;
                bestMask = mask;
                /* 自适应迭代 */
                double w = static_cast<double>(bestInliers)/N;
                maxIter = static_cast<int>(
                    std::log(1-prob)/std::log(1-std::pow(w,3))) + 1;
            }
        }
        ++iter;
        if(bestInliers >= minInliers) break;
    }

    /* 4. 最终非线性优化(可选,面试写骨架即可) */
    // refinePose(bestT, matches, bestMask);
    return bestT;
}

关键注释

  1. computeP3P内部需用**Eigen的Matrix<double,3,16,RowMajor>**缓存中间多项式系数,避免new。
  2. 返回的Quaterniond已保证q.coeffs().norm()-1<1e-6,防止后续优化出现NaN。
  3. 若面试官追问退化场景,答:在computeP3P里先检查三点共线(面积<1e-4)或共面(法向模<1e-4),直接返回false触发重采样。

拓展思考

  1. 多线程加速:国内量产SLAM常把RANSAC拆成CPU线程池+TBB并行for,每个线程私有vector<char> mask,最后atomic_max汇总最佳。Eigen3.4已支持Eigen::ThreadPoolDevice,可写Tensor版,但面试只需提到思路。
  2. 与滑窗BA耦合:RANSAC输出的bestMask作为静态约束加入margination阶段,可显著降低虚假闭环。
  3. 深度学习替代:若公司已有PVNet或DSAC*,可答“RANSAC+P3P作为fallback,DL失败时<2 ms切回传统”,体现算法冗余设计意识,国内主机厂尤为看重。