目录
背景介绍
opencv 链接支持扩展第三方扩展模块链接,也支持python API wrapper,本文旨在说明如何扩展自定义的模块以及如何包装成为python API
如何编译
编译命令行
cd <path/to/opencv>mkdir build
cd build
cmake -D CMAKE_BUILD_TYPE=RELEASE \
-D PYTHON_DEFAULT_EXECUTABLE=$(python -c "import sys; print(sys.executable)") \
-D PYTHON3_EXECUTABLE=$(python -c "import sys; print(sys.executable)") \
-D PYTHON3_NUMPY_INCLUDE_DIRS=$(python -c "import numpy; print (numpy.get_include())") \
-D PYTHON3_PACKAGES_PATH=$(python -c "from distutils.sysconfig import get_python_lib; print(get_python_lib())") \
-D CMAKE_CXX_FLAGS="-std=c++11"
安装python cv
cd <path/to/opencv>/build/python_loader
python setup.py install
#指定自定义的cv 路径,config-3.7.py 指定了cpython绑定的so,config.py指定了opencv的c实现lib
export PYTHONPATH=/usr/lib/python3.7/site-packages/opencv-4.5.3-py3.7.egg/
验证测试
#import sys
#setattr(sys, 'OpenCV_LOADER_DEBUG', Ture) Debug cv2的load 过程
import cv2 as cv
print(cv.__version__) #此处打印自己编译的cv 版本
自定义扩展
opencv_contrib/modules/hellotest/tree
#CMakeLists.txt
ocv_define_module(hellotest
opencv_core
opencv_imgproc
WRAP python
)
//include/opencv2/hellotest.hpp
#ifndef __HELLO_TEST_H__
#define __HELLO_TEST_H__
#include <opencv2/core.hpp>
namespace cv {
namespace hellotest {
CV_EXPORTS_W void helloWorld();
}
}
#endif
//hellotest.cpp
#include <opencv2/hellotest.hpp>
#include <stdio.h>
namespace cv {
namespace hellotest {
void helloWorld() {
printf("hello world zhenghua");
}
}
}
编译自定义扩展
cd <path/to/opencv/build
rm -rf * #删除里面原来的内容
cmake -D CMAKE_BUILD_TYPE=RELEASE \
-D PYTHON_DEFAULT_EXECUTABLE=$(python -c "import sys; print(sys.executable)") \
-D PYTHON3_EXECUTABLE=$(python -c "import sys; print(sys.executable)") \
-D PYTHON3_NUMPY_INCLUDE_DIRS=$(python -c "import numpy; print (numpy.get_include())") \
-D PYTHON3_PACKAGES_PATH=$(python -c "from distutils.sysconfig import get_python_lib; print(get_python_lib())") \
-D CMAKE_CXX_FLAGS="-std=c++11" \
-DOPENCV_EXTRA_MODULES_PATH=opencv_contrib/modules
关键是通过-DOPENCV_EXTRA_MODULES_PATH=opencv_contrib/modules 指定扩展module的路径
可以通过查看opencv/build/modules/python_bindings_generator 下面查看的文件判断自定义module 的API有没有被加入
编译后通过ldd查看自定义的module有没有被opencv的python binding模块cv2.cpython-37m-x86_64-linux-gnu.so 依赖
opencv/build$ ldd lib/python3/cv2.cpython-37m-x86_64-linux-gnu.so | grep hello
libopencv_hellotest.so.4.5 => opencv/build/lib/libopencv_hellotest.so.4.5 (0x00007fbc3b481000)
测试程序
指定python使用自定义的cv2
export PYTHONPATH=/usr/lib/py37/lib/python3.7/site-packages/opencv-4.5.3-py3.7.egg
import cv2 as cv
cv.hellotest.helloWorld()
关于opencv中c/c++ 如何与python做binding的官方文档说明链接