下载pybind
pip install pybind11
创建cpp文件
//以main.cpp为例
#include<iostream>
#include<pybind11/pybind11.h>
#include <pybind11/numpy.h>
#include<opencv2/opencv.hpp>
int add(int i, int j) {
return i + j;
}
//C++ Mat ->numpy
pybind11::array_t<unsigned char> cv_mat_uint8_1c_to_numpy(cv::Mat& input) {
pybind11::array_t<unsigned char> dst = pybind11::array_t<unsigned char>({ input.rows,input.cols }, input.data);
return dst;
}
//C++ Mat ->numpy
pybind11::array_t<unsigned char> cv_mat_uint8_3c_to_numpy(cv::Mat& input) {
pybind11::array_t<unsigned char> dst = pybind11::array_t<unsigned char>({ input.rows,input.cols,3}, input.data);
return dst;
}
std::tuple<int,pybind11::array_t<uint8_t>> ReadImage()
{
//读取并返回一张图片
pybind11::array_t<uint8_t> output_array;
cv::Mat img;
img = cv::imread("/home/HwHiAiUser/zyx/bus.jpg");
if(img.empty())
return std::tuple<int,pybind11::array_t<uint8_t>>(0,output_array);
output_array = cv_mat_uint8_3c_to_numpy(img);
return std::tuple<int,pybind11::array_t<uint8_t>>(1,output_array);
}
PYBIND11_MODULE(pycv, m) {
m.doc() = "pybind11 pycv plugin"; // optional module docstring
m.def("add", &add, "A function which adds two numbers");
m.def("GetResImage", &ReadImage,"读取一张图片");
}
创建CMakeLists.txt文件
cmake_minimum_required(VERSION 3.4)
project(example)
find_package(Python 3.8 COMPONENTS Interpreter Development REQUIRED)
include_directories(${PYTHON_INCLUDE_DIRS})
find_package(pybind11 REQUIRED PATHS /usr/local/lib/python3.8/dist-packages/pybind11/share/cmake/pybind11 NO_DEFAULT_PATH)
include_directories(${pybind11_INCLUDE_DIRS})
pybind11_add_module(pycv main.cpp)
set(OpenCV_DIR /usr/local/lib/cmake/opencv4)
find_package(OpenCV REQUIRED)
include_directories(${OpenCV_INCLUDE_DIRS})
message("--------------${OpenCV_DIR}---------------------")
message(STATUS "OpenCV library status:")
message(STATUS " version: ${OpenCV_VERSION}")
message(STATUS " libraries: ${OpenCV_LIBS}")
message(STATUS " include path: ${OpenCV_INCLUDE_DIRS}")
message("libs:--->${OpenCV_LIBRARIES}")
message("----------------opencv end----------------------")
target_link_libraries(pycv PUBLIC ${OpenCV_LIBRARIES})
编译
mkdir build
cd build
cmake ..
make -j4
python调用
import pycv
import cv2
print(pycv.add(1,2))
ret,img = pycv.GetResImage()
print(f'{ret},{img.shape}')
cv2.imshow("img",img)
cv2.waitKey(0)