C++ 是一种编译型(compiled)语言,设计重点是性能、效率和使用灵活性,偏向于系统编程、嵌入式、资源受限的软件和系统。html
Python是一种解释型(interpreted)语言,一样也支持不一样的编程范式。Python 内置了经常使用数据结构(str, tuple, list, dict),简洁的语法、丰富的内置库(os,sys,urllib,...)和三方库(numpy, tf, torch ...),功能强大。最为重要的是和可以和多种服务(flask…)和tensorflow、pytorch等无缝联合,从而方便将你的算法开放出去。python
一方面,咱们须要编译型语言(C++)性能;一方面,也须要解释型语言(Python)的灵活。这时,pybind11 能够用做 C++ 和 Python 之间沟通的桥梁。ios
Pybind11 是一个轻量级只包含头文件的库,用于 Python 和 C++ 之间接口转换,能够为现有的 C++ 代码建立 Python 接口绑定。Pybind11 经过 C++ 编译时的自省来推断类型信息,来最大程度地减小传统拓展 Python 模块时繁杂的样板代码, 已经实现了 STL 数据结构、智能指针、类、函数重载、实例方法等到Python的转换,其中函数能够接收和返回自定义数据类型的值、指针或引用。算法
因为在Windows上和在Linux上使用会有较大不一样,因此我这里将分为两个部分来讲明问题,本文为上篇,具体说明Windows+VS实现编程
一、vs的最简单调用flask
新建立项目,作如下修改:数组


# include <iostream >
# include <pybind11 /pybind11.h >
namespace py = pybind11;
PYBIND11_MODULE(example, m) {
m.doc() = "pybind11 example module";
// Add bindings here
m.def( "foo", []() {
return "Hello, World!";
});
}
PYBIND11_MODULE()
macro creates a function that will be called when an
import
statement is issued from within Python. The module name (
example
) is given as the first macro argument (it should not be in quotes). The second argument (
m
) defines a variable of type
py::module
which is the main interface for creating bindings. The method
module::def()
generates binding code that exposes the
add()
function to Python.


1.PYD是一种PYTHON动态模块。
2.实质上仍是dll文件,只是改了后缀为PYD。
这里特别须要注意,就是.pyd文件名和GOPyWarper这个函数名字必定要同样,不然报数据结构
错误。app
二、vs添加OpenCV的调用函数
配置中,须要添加OpeCV部分。分别是附加包含目录和附加依赖项。


//
# include "pch.h"
# include <iostream >
# include <opencv2 /core.hpp >
# include <opencv2 /imgcodecs.hpp >
# include <opencv2 /imgproc.hpp >
# include <opencv2 /highgui.hpp >
# include <pybind11 /pybind11.h >
using namespace cv;
using namespace std;
namespace py = pybind11;
PYBIND11_MODULE(example, m) {
m.doc() = "pybind11 example module";
// Add bindings here
m.def( "foo", [](string strPath) {
Mat src = imread(strPath);
Mat gray;
cvtColor(src, gray, COLOR_BGR2GRAY);
imshow( "gray", gray);
waitKey( 0); //必须设置,不然卡死
return "Hello, OpenCV!";
});
}
var1 = GOPyWarper.test_rgb_to_gray(src)
cv2.imshow( 'gray',var1)




py::list out;



//输出结果
py : :list out;
……