文章目录
- 软件环境
- 1.编译python3的cv_bridge
- 2.创建基于python3的图像ROS节点
- (1)初始化py3_test_ws工作空间
- (2)创建功能包
- (3)编写python3的图像发布和接收节点
- 摄像头发布节点
- 摄像头接收处理节点
- 3.运行节点
- (1)编译
- (2)将工作空间添加进环境变量
- (3)运行节点
- 运行效果图
亲测可行,如有疑惑,直接先跳到最后查看效果图~所使用的python为3.6.9。
软件环境
-
Ubuntu18.04
-
python3.6.9
-
ROS Melodic
Jetson系列基础环境配置:Jetson系列——Ubuntu18.04版本基础配置(换源、ROS、远程桌面、开机自连WIFi、SD卡备份)
树莓派环境配置:树莓派4B——Ubuntu 18.04.05安装和基础配置教程(包括WIFI和远程桌面配置、ROS和主从机控制)
虚拟机环境配置:Ubuntu——双系统Ubuntu18.04系统安装和基础配置并安装ROS
1.编译python3的cv_bridge
- ROS——基于Ubuntu18.04和ROS Melodic编译python3的cv_bridge
2.创建基于python3的图像ROS节点
(1)初始化py3_test_ws工作空间
mkdir py3_test_ws && cd py3_test_ws
mkdir src && cd src
catkin_init_workspace
(2)创建功能包
catkin_create_pkg py3_demo rospy rosmsg roscpp
(3)编写python3的图像发布和接收节点
cd py3_demo && mkdir scripts
cd scripts && touch camera.py img_process.py
chmod +x camera.py
chmod +x img_process.py
将以下两个节点代码分别粘进对应的文件中:
摄像头发布节点
camera.py
#!/usr/bin/env python3
# coding:utf-8
import cv2
import numpy as np
import rospy
from std_msgs.msg import Header
from sensor_msgs.msg import Image
from cv_bridge import CvBridge , CvBridgeError
import time
if __name__=="__main__":
import sys
print(sys.version) # 查看python版本
capture = cv2.VideoCapture(0) # 定义摄像头
rospy.init_node('camera_node', anonymous=True) #定义节点
image_pub=rospy.Publisher('/image_view/image_raw', Image, queue_size = 1) #定义话题
while not rospy.is_shutdown(): # Ctrl C正常退出,如果异常退出会报错device busy!
start = time.time()
ret, frame = capture.read()
if ret: # 如果有画面再执行
# frame = cv2.flip(frame,0) #垂直镜像操作
frame = cv2.flip(frame,1) #水平镜像操作
ros_frame = Image()
header = Header(stamp = rospy.Time.now())
header.frame_id = "Camera"
ros_frame.header=header
ros_frame.width = 640
ros_frame.height = 480
ros_frame.encoding = "bgr8"
# ros_frame.step = 1920
ros_frame.data = np.array(frame).tostring() #图片格式转换
image_pub.publish(ros_frame) #发布消息
end = time.time()
print("cost time:", end-start ) # 看一下每一帧的执行时间,从而确定合适的rate
rate = rospy.Rate(25) # 10hz
capture.release()
cv2.destroyAllWindows()
print("quit successfully!")
摄像头接收处理节点
img_process.py
#!/usr/bin/env python3
# coding:utf-8
import rospy
import numpy as np
from sensor_msgs.msg import Image
from cv_bridge import CvBridge, CvBridgeError
import cv2
def callback(data):
global bridge
cv_img = bridge.imgmsg_to_cv2(data, "bgr8")
cv2.imshow("frame" , cv_img)
cv2.waitKey(1)
if __name__ == '__main__':
import sys
print(sys.version) # 查看python版本
rospy.init_node('img_process_node', anonymous=True)
bridge = CvBridge()
rospy.Subscriber('/image_view/image_raw', Image, callback)
rospy.spin()
3.运行节点
(1)编译
cd ../../..
catkin_make -DPYTHON_EXECUTABLE=/usr/bin/python3
(2)将工作空间添加进环境变量
sudo vim ~/.bashrc
source /home/nano/workspace/py3_test_ws/devel/setup.bash
(3)运行节点
roscore
rosun py3_demo camera.py
rosun py3_demo img_process.py
运行效果图
可以看到,打印出的python版本为3.6.9
: