python语言灵活易用,但是有时效率较低,c++效率较高,pybind可以较好的结合两者。
在c++代码中引入pybind11相关库,pybind可以利用buffer将python中的一些数据类型转化为c++可用的类型。如下代码:
#include<iostream>
#include<vector>
#include<opencv2/core/core.hpp>
#include<opencv2/imgproc/imgproc.hpp>
#include<opencv2/highgui/highgui.hpp>
#include<pybind11/pybind11.h>
#include<pybind11/numpy.h>
#include<pybind11/stl.h>
#include"mat_warper.h"
#include<pybind11/eigen.h>
#include<eigen3/Eigen/Dense>
namespace py = pybind11;
using namespace std;
using namespace cv;
Mat numpy_uint8_1c_to_cv_mat(py::array_t<unsigned char>& input) {
if (input.ndim() != 2)
throw std::runtime_error("1-channel image must be 2 dims ");
py::buffer_info buf = input.request();
cv::Mat mat(buf.shape[0], buf.shape[1], CV_8UC1, (unsigned char*)buf.ptr);
return mat;
}
int test_im(py::array_t<unsigned char>& input) {
Mat img_rgb = numpy_uint8_1c_to_cv_mat(input);
Mat dst;
cout << img_rgb.size()<<endl;
cvtColor(img_rgb, dst, COLOR_RGB2GRAY);
return 1;
}
int test_eigen(Eigen::Ref<const Eigen::MatrixXd> &coord) {
cout <<&coord<<endl;
cout <<coord(2,1) <<endl;
cout <<coord(1,2) <<endl;
return 1;
}
PYBIND11_MODULE(test_main, m) {
m.doc() = "Simple opencv demo";
m.def("test_im", &test_im);
m.def("test_eigen", &test_eigen);
}
利用cmake、make将c++脚本转换为so文件,直接import test_main即可
欢迎关注
版权声明:本文为bea_tree原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。