Using Cython to port a C ++ class using OpenCV types as parameters
I am trying to use Cython to port a C ++ class that uses some OpenCV types as parameters, then I intend to use this wrapped class from Python. A simplified version of the C ++ class looks like this:
"transform.h"
#include "opencv2/core/core.hpp"
namespace geom
{
class Transform
{
public:
Transform(cv::Vec3d &euler, cv::Vec3d &t);
void set_euler(cv::Vec3d &euler);
cv::Vec3d get_euler();
}
}
Vec3d is defined in OpenCV as:
template<typename _Tp, int n> class Vec : public Matx<_Tp, n, 1> {...};
typedef Vec<double, 3> Vec3d;
and Matx is defined as:
template<typename _Tp, int m, int n> class Matx {...};
My first attempt at a cython shell looks like this:
"geom_gateway.pyx"
cdef extern from "opencv2/core/core.hpp" namespace "cv":
cdef cppclass Matx[_Tp, int m, int n]:
Matx()
Matx(_Tp v0, _Tp v1, _Tp v2)
cdef extern from "opencv2/core/core.hpp" namespace "cv":
cdef cppclass Vec[_Tp, int n](Matx[_Tp, n, 1]):
Vec()
Vec(_Tp v0, _Tp v1, _Tp v2)
ctypedef Vec<double, 3> Vec3d
cdef extern from "transform.h" namespace "geom":
cdef cppclass Transform:
Transform(cv::Vec3d &euler, cv::Vec3d &t)
void set_euler(cv::Vec3d &euler)
cv::Vec3d get_euler()
This shell is incomplete, but I just wanted to create it and check that I understand the syntax correctly. Unfortunately, when I build it I didn't go too far, I get:
cdef extern from "opencv2/core/core.hpp" namespace "cv":
cdef cppclass Matx[_Tp, int m, int n]:
^
------------------------------------------------------------
../basics/geom_gateway:3:29: Expected ']', found 'm'
what's wrong? I suppose it is possible to have multiple value patterns in Cython? otherwise how could I wrap a C ++ class in Cython that uses these template types from OpenCV? I suspect I may have other issues in this code snippet, please feel free to point out.
source to share
I found a solution! based on this thread:
Instead of declaring templates in cython, I can declare a specific case in C ++ in quotes and then use that variable to call my cython variable. For Vec3d it will be:
cdef extern from "opencv2/core/core.hpp" namespace "cv":
cdef cppclass Vec3d "cv::Vec<double, 3>":
Vec3d()
Vec3d(double v0, double v1, double v2)
Please note that the "cv" namespace must be inside quotes or it will not work. and for Matx33d
cdef extern from "opencv2/core/core.hpp" namespace "cv":
cdef cppclass Matx33d "cv::Matx<double, 3, 3>":
Matx33d()
Matx33d(double v0, double v1, double v2, double v3, double v4, double v5, double v6, double v7, double v8)
source to share