- Clone packages
cd lib
git clone https://github.com/pybind/pybind11.git
- CmakeList.txt
add_subdirectory(lib/pybind11)
catkin_python_setup() # 需要setup.py
# https://pybind11.readthedocs.io/en/stable/advanced/embedding.html
add_library(segmentor_lib SHARED
include/sensor/camera/segmentor/segmentor.cpp)
target_link_libraries(segmentor_lib pybind11::embed ${catkin_LIBRARIES}
${OpenCV_LIBS}
${TORCH_LIBRARIES}
)
package.xml
<build_depend>pybind11_catkin</build_depend>
<exec_depend>pybind11_catkin</exec_depend>
setup.py
与CMakeList.txt
同层
# ! DO NOT MANUALLY INVOKE THIS setup.py, USE CATKIN INSTEAD
from distutils.core import setup
from catkin_pkg.python_setup import generate_distutils_setup
# fetch values from package.xml
# https://zhuanlan.zhihu.com/p/58382081
setup_args = generate_distutils_setup(
packages=['segmentor'],
package_dir={'': 'include/sensor/camera'})
setup(**setup_args)
Usage
py_interpreter = std::make_shared<py::scoped_interpreter>(); // start the interpreter and keep it alive
sys = py::module_::import("sys");
py::print(sys.attr("executable"));
py::print(sys.attr("path"));
mmsegmentor = py::module::import("segmentor.mmsegmentor").attr("Segmentor")(CONFIG_PATH, CHECKPOINT_PATH, DEVICE);
编译和运行的时候都需要先激活虚拟环境
conda activate open-mmlab
https://github.com/jianhengLiu/SV-SLAM/blob/cbc0f9278a5d6e31ba43f11f0209a1dd3ab0b965/include/sensor/image/segmentor/segmentor.cpp