前言
在之前的pybind11系列實(shí)踐中,開發(fā)流程大致是這樣的:
- 第一步: 首先在C/C++ IDE中編寫C/C++函數(shù),然后采用pybind11封裝為python可調(diào)用的包裝函數(shù), 之后采用C/C++編譯器生成.pyd文件

- 第二步:將生成的.pyd文件復(fù)制到python工程中,之后作為python module import導(dǎo)入使用
image.png
存在的問題
不同操作系統(tǒng)下直接調(diào)用生成的pyd可能會(huì)出錯(cuò),不能跨平臺(tái)調(diào)用
在上述過程中,pyd動(dòng)態(tài)鏈接庫的生成是在本地PC上,但是如果想在不同的操作系統(tǒng)、硬件平臺(tái)上調(diào)用之前生成的pyd,顯然是會(huì)出錯(cuò)的。比如在windows上編譯生成了一個(gè)python擴(kuò)展.pyd, 但是Ubuntu系統(tǒng)或者樹莓派上想調(diào)用這個(gè)python擴(kuò)展顯然就不行了。
為了使得C/C++創(chuàng)建的python擴(kuò)展可以跨平臺(tái)使用,那么最簡(jiǎn)單的辦法就是直接發(fā)布源碼, 然后在該操作系統(tǒng)、硬件平臺(tái)上編譯生成python擴(kuò)展。
本節(jié)內(nèi)容利用python setuptools 方式實(shí)現(xiàn)
pybind11系列文章:
http://www.itdecent.cn/p/82a5748ed0fb
開發(fā)環(huán)境
- windows 10 64bit
- Anaconda3, with python 3.7
- pybind11
C/C++ python擴(kuò)展的實(shí)現(xiàn)
Project1
創(chuàng)建一個(gè)簡(jiǎn)單的工程, 之后創(chuàng)建一個(gè)package,取名demo1:

創(chuàng)建如下文件:
-
__init__.py創(chuàng)建包默認(rèn)生成的 -
example.cppC++代碼 -
setup.py用于編譯C++代碼,生成C/C++ python擴(kuò)展 -
test.py測(cè)試
在Visual Studio中測(cè)試通過之后,將C/C++源碼文件添加的python工程目錄中,然后創(chuàng)建一個(gè)setup.py文件,編寫如下代碼:
在Extension中設(shè)置C/C++源碼文件、第三方庫的依賴文件,由于本工程采用pybind11進(jìn)行C++ 與python接口的封裝,因此需要包含pybind11庫的頭文件,pybind11庫是header-only,因此無需包含lib。
setup.py
from setuptools import setup
from setuptools import Extension
example_module = Extension(name='numpy_demo', # 模塊名稱
sources=['example.cpp'], # 源碼
include_dirs=[r'D:\Anaconda3_2\include', # 依賴的第三方庫的頭文件
r'D:\pybind11-master\include']
)
setup(ext_modules=[example_module])
example.cpp
#include<pybind11/pybind11.h>
#include<pybind11/numpy.h>
#include<fstream>
#include<iostream>
namespace py = pybind11;
/*
https://blog.csdn.net/u013701860/article/details/86313781
https://blog.csdn.net/u011021773/article/details/83188012
*/
py::array_t<float> calcMul(py::array_t<float>& input1, py::array_t<float>& input2) {
// read inputs arrays buffer_info
py::buffer_info buf1 = input1.request();
py::buffer_info buf2 = input2.request();
if (buf1.size != buf2.size)
{
throw std::runtime_error("Input shapes must match");
}
// allocate the output buffer
py::array_t<double> result = py::array_t<double>(buf1.size);
}
class Matrix
{
public:
Matrix() {};
Matrix(int rows, int cols) {
this->m_rows = rows;
this->m_cols = cols;
m_data = new float[rows*cols];
}
~Matrix() {};
private:
int m_rows;
int m_cols;
float* m_data;
public:
float* data() { return m_data; };
int rows() { return m_rows; };
int cols() { return m_cols; };
};
void save_2d_numpy_array(py::array_t<float, py::array::c_style> a, std::string file_name) {
std::ofstream out;
out.open(file_name, std::ios::out);
std::cout << a.ndim() << std::endl;
for (int i = 0; i < a.ndim(); i++)
{
std::cout << a.shape()[i] << std::endl;
}
for (int i = 0; i < a.shape()[0]; i++)
{
for (int j = 0; j < a.shape()[1]; j++)
{
if (j == a.shape()[1]-1)
{
//訪問讀取,索引 numpy.ndarray 中的元素
out << a.at(i, j)<< std::endl;
}
else {
out << a.at(i, j) << " ";
}
}
}
}
//
//py::array_t<unsigned char, py::array::c_style> rgb_to_gray(py::array_t<unsigned char, py::array::c_style>& a) {
//
// py::array_t<unsigned char, py::array::c_style> dst = py::array_t<unsigned char, py::array::c_style>(a.shape()[0] * a.shape()[1]);
// //指針訪問numpy矩陣
// unsigned char* p = (unsigned char*)dst.ptr();
//
// for (int i = 0; i < a.shape()[0]; i++)
// {
// for (int j = 0; j < a.shape()[1]; j++)
// {
// auto var = a.data(i, j);
// auto R = var[0];
// auto G = var[1];
// auto B = var[2];
//
// //RGB to gray
// auto gray = (R * 30 + G * 59 + B * 11 + 50) / 100;
//
// std::cout << static_cast<int>(R) << " " << static_cast<int>(G) << " " << static_cast<int>(B)<< std::endl;
//
// //p[i*a.shape()[1] + j] = static_cast<unsigned char>(gray);
//
// }
// }
//}
PYBIND11_MODULE(numpy_demo, m) {
m.doc() = "Simple numpy demo";
py::class_<Matrix>(m,"Matrix",py::buffer_protocol())
.def_buffer([](Matrix& mm)->py::buffer_info {
return py::buffer_info(
mm.data(), //Pointer to buffer, 數(shù)據(jù)指針
sizeof(float), //Size of one scalar, 每個(gè)元素大小(byte)
py::format_descriptor<float>::format(), //python struct-style foramt descriptor
2, //Number of dims, 維度
{mm.rows(), mm.cols()}, //strides (in bytes)
{sizeof(float) * mm.cols(),sizeof(float)}
);
});
m.def("save_2d_numpy_array", &save_2d_numpy_array);
//m.def("rgb_to_gray", &rgb_to_gray);
}
在pycharm底下,打開終端:

將路徑切換到setup.py所在目錄,然后執(zhí)行命令:

生成python擴(kuò)展庫:


最后,會(huì)發(fā)現(xiàn)工程中增加了一些新的目錄和文件,其中xxxx.pyd就是生成的python擴(kuò)展庫。

- python擴(kuò)展庫測(cè)試
test.py
import demo1.numpy_demo as numpy_demo
import numpy as np
help(numpy_demo)
mat1 = numpy_demo.save_2d_numpy_array(np.zeros(shape=[10,10], dtype=np.float32), r'./data.dat')
print(mat1)



Project2 opencv工程
第一個(gè)工程比較簡(jiǎn)單,沒有包含和依賴第三方庫,一般C/C++工程中,往往包含和依賴許多第三方庫,本工程以opencv庫為例,實(shí)現(xiàn)C/C++ python擴(kuò)展模塊的編譯。

編寫setup.py
from setuptools import Extension
from setuptools import setup
__version__ = '0.0.1'
# 擴(kuò)展模塊
ext_module = Extension(
# 模塊名稱
name='cv_demo1',
# 源碼
sources=[r'mat_warper.cpp', r'main.cpp'],
# 包含頭文件
include_dirs=[r'D:\Anaconda3_2\include',
r'D:\opencv-4.1.0\opencv\build\include',
r'D:\pybind11-master\include'
],
# 庫目錄
library_dirs=[r'D:\opencv-4.1.0\opencv\build\x64\vc15\lib'],
# 鏈接庫文件
libraries=[r'opencv_world410'],
language='c++'
)
setup(
name='cv_demo1',
version=__version__,
author_email='xxxx@qq.com',
description='A simaple demo',
ext_modules=[ext_module],
install_requires=['numpy']
)
編譯python擴(kuò)展庫:
在終端執(zhí)行命令


python代碼測(cè)試:
test.py
import demo2.cv_demo1 as cv_demo
import numpy as np
import cv2
import matplotlib.pyplot as plt
help(cv_demo)
image = cv2.imread(r'F:\lena\lena_gray.jpg', cv2.IMREAD_GRAYSCALE)
# canny
img_canny = cv_demo.test_gray_canny(image)
plt.figure('canny')
plt.imshow(img_canny, cmap=plt.gray())
# pyramid
imgs_pyramid = cv_demo.test_pyramid_image(image)
plt.figure('pyramid')
for i in range(1, len(imgs_pyramid)):
plt.subplot(2, 2, i)
plt.imshow(imgs_pyramid[i])
# rgb to gray
plt.figure('rgb->gray')
img_gray = cv_demo.test_rgb_to_gray(cv2.imread(r'F:\lena\lena_rgb.jpg'))
plt.imshow(img_gray)
plt.show()
python測(cè)試結(jié)果:
-
canny邊緣檢測(cè)
image.png -
Gaussian圖像金字塔
image.png -
圖像RGB轉(zhuǎn)Gray
image.png
C++源碼:
main.cpp
#include<iostream>
#include<vector>
#include<opencv2/opencv.hpp>
#include<pybind11/pybind11.h>
#include<pybind11/numpy.h>
#include<pybind11/stl.h>
#include"mat_warper.h"
namespace py = pybind11;
py::array_t<unsigned char> test_rgb_to_gray(py::array_t<unsigned char>& input) {
cv::Mat img_rgb = numpy_uint8_3c_to_cv_mat(input);
cv::Mat dst;
cv::cvtColor(img_rgb, dst, cv::COLOR_RGB2GRAY);
return cv_mat_uint8_1c_to_numpy(dst);
}
py::array_t<unsigned char> test_gray_canny(py::array_t<unsigned char>& input) {
cv::Mat src = numpy_uint8_1c_to_cv_mat(input);
cv::Mat dst;
cv::Canny(src, dst, 30, 60);
return cv_mat_uint8_1c_to_numpy(dst);
}
/*
@return Python list
*/
py::list test_pyramid_image(py::array_t<unsigned char>& input) {
cv::Mat src = numpy_uint8_1c_to_cv_mat(input);
std::vector<cv::Mat> dst;
cv::buildPyramid(src, dst, 4);
py::list out;
for (int i = 0; i < dst.size(); i++)
{
out.append<py::array_t<unsigned char>>(cv_mat_uint8_1c_to_numpy(dst.at(i)));
}
return out;
}
PYBIND11_MODULE(cv_demo1, m) {
m.doc() = "Simple opencv demo";
m.def("test_rgb_to_gray", &test_rgb_to_gray);
m.def("test_gray_canny", &test_gray_canny);
m.def("test_pyramid_image", &test_pyramid_image);
}
mat_warper.h
#ifndef MAT_WARPER_H_
#include<opencv2/opencv.hpp>
#include<pybind11/pybind11.h>
#include<pybind11/numpy.h>
namespace py = pybind11;
cv::Mat numpy_uint8_1c_to_cv_mat(py::array_t<unsigned char>& input);
cv::Mat numpy_uint8_3c_to_cv_mat(py::array_t<unsigned char>& input);
py::array_t<unsigned char> cv_mat_uint8_1c_to_numpy(cv::Mat & input);
py::array_t<unsigned char> cv_mat_uint8_3c_to_numpy(cv::Mat & input);
#endif // !MAT_WARPER_H_
mat_warper.cpp
#include"mat_warper.h"
#include <pybind11/numpy.h>
/*
Python->C++ Mat
*/
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;
}
cv::Mat numpy_uint8_3c_to_cv_mat(py::array_t<unsigned char>& input) {
if (input.ndim() != 3)
throw std::runtime_error("3-channel image must be 3 dims ");
py::buffer_info buf = input.request();
cv::Mat mat(buf.shape[0], buf.shape[1], CV_8UC3, (unsigned char*)buf.ptr);
return mat;
}
/*
C++ Mat ->numpy
*/
py::array_t<unsigned char> cv_mat_uint8_1c_to_numpy(cv::Mat& input) {
py::array_t<unsigned char> dst = py::array_t<unsigned char>({ input.rows,input.cols }, input.data);
return dst;
}
py::array_t<unsigned char> cv_mat_uint8_3c_to_numpy(cv::Mat& input) {
py::array_t<unsigned char> dst = py::array_t<unsigned char>({ input.rows,input.cols,3}, input.data);
return dst;
}
//PYBIND11_MODULE(cv_mat_warper, m) {
//
// m.doc() = "OpenCV Mat -> Numpy.ndarray warper";
//
// m.def("numpy_uint8_1c_to_cv_mat", &numpy_uint8_1c_to_cv_mat);
// m.def("numpy_uint8_1c_to_cv_mat", &numpy_uint8_1c_to_cv_mat);
//
//
//}



