前言
我的环境是ubuntu18.04+ros-melodic+python3.8
以下是使用过程的代码:
bridge = CvBridge()
img = bridge.imgmsg_to_cv2(img_msg)
会出现下面错误,产生错误原因无非是ros对python3的兼容性不友好。
File "/opt/ros/melodic/lib/python2.7/dist-packages/cv_bridge/core.py", line 91, in encoding_to_cvtype2
from cv_bridge.boost.cv_bridge_boost import getCvType
ImportError: dynamic module does not define module export function (PyInit_cv_bridge_boost)
解决办法
以下是我的解决方法(亲测有效):
sudo apt-get install python-catkin-tools python3-dev python3-catkin-pkg-modules python3-numpy python3-yaml ros-melodic-cv-bridge
# Create catkin workspace
mkdir catkin_ws
cd catkin_ws
catkin init
# Instruct catkin to set cmake variables
catkin config -DPYTHON_EXECUTABLE=/usr/bin/python3 -DPYTHON_INCLUDE_DIR=/usr/include/python3.6m -DPYTHON_LIBRARY=/usr/lib/aarch64-linux-gnu/libpython3.6m.so
# Instruct catkin to install built packages into install place. It is $CATKIN_WORKSPACE/install folder
catkin config --install
# Clone cv_bridge src
git clone https://github.com/ros-perception/vision_opencv.git src/vision_opencv
# Find version of cv_bridge in your repository
apt-cache show ros-melodic-cv-bridge | grep Version
# Version: 1.13.0-0bionic.20220127.152918
cd src/vision_opencv/
git checkout 1.13.0
cd ../../
# Build
# catkin clean --yes
catkin build cv_bridge
# Extend environment with new package
source install/setup.bash --extend
其他解决方法,有人推荐用numpy/ros_numpy代替cv_bridge去实现,大家也可以去尝试下。
import numpy as np
img = np.frombuffer(image_data.data, dtype=np.uint8).reshape(image_data.height, image_data.width, -1)
# Beautiful solution is to use ros_numpy. It is similar to the function of cv_bridge, but without the dependency on cv2:
import ros_numpy
np_img = ros_numpy.numpify(ros_img_msg)