使用Eigen计算两条直线的交点

3
今天我开始接触eigen,发现以下方法可以获取交点:
#include <Eigen/Dense>
using namespace Eigen;
using namespace std;

int main() {
    // Calc intersection of line ac with bd:
    Vector2f a(8,2);
    Vector2f b(9,5);
    Vector2f c(6,6);
    Vector2f d(5,9);

    Matrix2f xx; 
    xx << c-a, b-d; 

    cout << "Here is the matrix xx:\n" << xx << endl;
    Vector2f x = xx.colPivHouseholderQr().solve(b-a);
    Vector2f intersect1( a + x(0)* ( c-a ) );
    Vector2f intersect2( b + x(1)* ( d-b ) );

    cout << "intersect1\n" << intersect1 << std::endl;
    cout << "intersect2\n" << intersect2 << std::endl;
}

问:Eigen库中是否有一个函数可以直接给出交点的结果?我认为我在这里做了太多手工编码。


3
我认为这个问题最好在代码审查网站上询问,因为这是可行的代码。 - UKMonkey
@NicoSchertler:如果是这样,那太好了;) 谢谢!把它作为答案来赚取一些积分吧;) - Klaus
1
@NicoSchertler 尽管代码不多,但实现时存在许多机会出错(错误符号、忽略(近)奇异性等)。 - chtz
1个回答

13
在二维坐标系中,一条直线等同于一个超平面。对于这种情况,有一个intersection方法:
#include <Eigen/Geometry>
#include <iostream>
int main() {
    using Line2 = Eigen::Hyperplane<float,2>;
    using Vec2  = Eigen::Vector2f;
    Vec2 a(8,2);
    Vec2 b(9,5);
    Vec2 c(6,6);
    Vec2 d(5,9);

    Line2 ac = Line2::Through(a,c);
    Line2 bd = Line2::Through(b,d);

    std::cout << "Intersection:\n" << ac.intersection(bd) << '\n';
}

你的代码和结果都是[4, 10]


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接