发布和订阅 image
- 打开摄像头
- 发布图片
- 订阅图片
- cv_bridge
打开摄像头
cap = cv2.VideoCapture("/dev/video0")
cap.set(3, 640)
cap.set(4, 480)
ret, frame = cap.read()
发布图片
image_pub = rospy.Publisher('/image', Image,queue_size=10)
image_pub.publish(bridge.cv2_to_imgmsg(frame, "bgr8"))
订阅图片
rospy.Subscriber("/image", Image,image_callback,queue_size = 10)
def image_callback(image_data):
global bridge,count
frame = bridge.imgmsg_to_cv2(image_data, "bgr8")
image_name = str(count) + ".jpg"
cv2.imwrite(image_path + image_name, frame)
print("图片保存成功:",image_name)
rospy.Rate(20).sleep()
count+=1
cv_bridge
- 这里发布和订阅图片都用到python3的cv_bridge进行图片类型转换
- 由于Ubuntu16.04和Ubuntu18.04 python默认版本为python2,所以使用python2的cv_bridge会报错
- 需要下载vision_opencv,并编译,就可以使用下图的cv_bridge,具体教程参考博客
- 可以下载我分别在Ubuntu16.04和Ubuntu18.04编译生成的cv_bridge
sys.path.remove("/opt/ros/kinetic/lib/python2.7/dist-packages")
sys.path.append("/home/bo/catkin_ws/src/racecar/racecar_gazebo/scripts/")
from cv_bridge import CvBridge, CvBridgeError
import time
import rospy
import sys
import cv2
import numpy as np
import math
from sensor_msgs.msg import Image
sys.path.remove("/opt/ros/kinetic/lib/python2.7/dist-packages")
sys.path.append("/home/bo/catkin_ws/src/racecar/racecar_gazebo/scripts/")
from cv_bridge import CvBridge, CvBridgeError
image_path = '/home/bo/data/'
count=0
def image_callback(image_data):
global bridge,count
frame = bridge.imgmsg_to_cv2(image_data, "bgr8")
image_name = str(count) + ".jpg"
cv2.imwrite(image_path + image_name, frame)
print("图片保存成功:",image_name)
rospy.Rate(20).sleep()
count+=1
def main():
try:
while not rospy.is_shutdown():
ret, frame = cap.read()
image_pub.publish(bridge.cv2_to_imgmsg(frame, "bgr8"))
cv2.imshow('frame', frame)
cv2.waitKey(3)
if cv2.waitKey(1) & 0xFF == 27:
break
cap.release()
cv2.destroyAllWindows()
except rospy.ROSInterruptException:
pass
if __name__ == '__main__':
try:
rospy.init_node('Server_Socket', anonymous=True)
global bridge,cap,image_pub
bridge = CvBridge()
cap = cv2.VideoCapture("/dev/video0")
cap.set(3, 640)
cap.set(4, 480)
image_pub = rospy.Publisher('/image', Image,queue_size=10)
rospy.Subscriber("/image", Image,image_callback,queue_size = 10)
main()
rospy.spin()
except rospy.ROSInterruptException:
pass