这里还是直接提供代码把。
首先,我在test_py包下的msg文件内有个Image.msg文件,内容与sensor_msgs/Image.msg一样。
Image.msg
Header header
uint32 height
uint32 width
string encoding
uint8 is_bigendian
uint32 step
uint8[] data
然后我的package文件如下:
test_py
0.0.0
The test_py package
smile
TODO
catkin
rospy
std_msgs
cv_bridge
sensor_msgs
message_generation
rospy
std_msgs
cv_bridge
sensor_msgs
message_runtime
我的CMakeLists.txt文件代码如下:
cmake_minimum_required(VERSION 2.8.3)
project(test_py)
find_package(catkin REQUIRED COMPONENTS
rospy
std_msgs
cv_bridge
sensor_msgs
message_generation
)
add_message_files(
FILES
test.msg
Image.msg
)
generate_messages(
DEPENDENCIES
test_py
sensor_msgs
)
catkin_package(
#INCLUDE_DIRS include
#LIBRARIES test_py
CATKIN_DEPENDS rospy cv_bridge message_runtime
DEPENDS system_lib
)
include_directories(
${catkin_INCLUDE_DIRS}
)
我的发布图片结点信息如下:
#!/usr/bin/env python
#coding:utf-8
import rospy
import sys
sys.path.append('.')
import cv2
import os
import numpy as np
from test_py.msg import Image
from cv_bridge import CvBridge, CvBridgeError
def pubImage():
rospy.init_node('pubImage',anonymous = True)
pub = rospy.Publisher('ShowImage', Image, queue_size = 10)
rate = rospy.Rate(10)
bridge = CvBridge()
gt_imdb = []
#path是我存放图片的文件夹
path = "../../../../test"
for item in os.listdir(path):
gt_imdb.append(os.path.join(path,item))
while not rospy.is_shutdown():
for imagepath in gt_imdb:
image = cv2.imread(imagepath)
image = cv2.resize(image,(900,450))
pub.publish(bridge.cv2_to_imgmsg(image,"bgr8"))
#cv2.imshow("lala",image)
#cv2.waitKey(0)
rate.sleep()
if __name__ == '__main__':
try:
pubImage()
except rospy.ROSInterruptException:
pass
我的接收图片结点代码如下:
#!/usr/bin/env python
#coding:utf-8
import rospy
import cv2
from test_py.msg import Image
from cv_bridge import CvBridge,CvBridgeError
def callback(data):
bridge = CvBridge()
cv_image = bridge.imgmsg_to_cv2(data,"bgr8")
cv2.imshow("lala",cv_image)
cv2.waitKey(0)
def showImage():
rospy.init_node('showImage',anonymous = True)
rospy.Subscriber('ShowImage', Image, callback)
rospy.spin()
if __name__ == '__main__':
showImage()
这里注释就不给了,感觉都是能一眼就知道是干吗的代码。
请原谅我是个懒惰的博主,然后有写的不好或者不对的地方,欢迎提出批评指正。