How to use pybind11 to convert between Eigen::Quaternion and numpy ndarray
Asked Answered
S

2

7

I am trying to wrap up a c++ function that takes in Eigen::Quaternion as the argument for python usage. The function is defined as something like:

void func(const Eigen::Quaternion<double> &rotation) {...}

I am using pybind11 to wrap it for python and in my pybind11 I have:

#include <pybind11/eigen.h> // I have this included

PYBIND11_MODULE(example, m)
{
    m.def("func", &func, "example function");
}

Everything looks good, it compiles, but when I call it by:

func(np.array([0, 0, 0, 1]))

I got error:

func(): incompatible function arguments. The following argument types are supported: 1. (arg0: Eigen::Quaternion<double,0>) -> None

Did some googling and could not find an answer regarding if Eigen::Quaternion can be casted to/from numpy array and what shape of the array should be used? I thought Quaternion can be just casted from a 4 element numpy ndarray but seem it is not, any one knows how to do that?

Swaim answered 9/2, 2021 at 20:45 Comment(1)
Hi, did you find a solution for this back then?Castano
H
0

The easiest way I've found is adding a small C++ wrapper converting Eigen::Matrix to Eigen::Quaternion like so:

void func(const Eigen::Quaternion<double> &rotation) {...}
#include <pybind11/eigen.h>

void func_wrapper(Eigen::Matrix<double, 4, 1> quat)
{
   func(Eigen::Quaternion<double>(q(0), q(1), q(2), q(3)));
}

PYBIND11_MODULE(example, m)
{
    m.def("func", &func_wrapper, "example function");
}

func(np.array([0, 0, 0, 1])) should work!

Hoopen answered 17/1 at 14:2 Comment(0)
C
-2

I think the issue is that eigen quat needs doubles and you have constructed your np.array with ints.

func(np.array([0.0, 0.0, 0.0, 1.0]))

will probably work?

Churchless answered 6/5, 2021 at 10:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.