方法:
- 自定义msgs:MyImage.msg
float64 time
int16[] size
uint8[] data
- 将cv2图片矩阵转为list赋值给msgs
#!/usr/bin/env python3
#coding=utf-8
import rospy
import cv2
from my_msgs.msg import MyImage
import numpy as np
def publish():
image = MyImage()
image.size = []
size = 0
while True:
cap = cv2.VideoCapture('/home/fly/catkin_ws/src/ssd_pkg/new.avi') # 视频
while cap.isOpened() and not rospy.is_shutdown():
ret, frame = cap.read()
if ret:
frame = cv2.resize(frame, (1280, 720), interpolation=cv2.INTER_LINEAR)
if not size:
image.size = list(frame.shape)
size = image.size[0]*image.size[1]*image.size[2]
image.data = frame.reshape(size).tolist() # 转一维list
image.time = rospy.get_time()
image_pub.publish(image)
print("publish one:",image.time)
if __name__ == '__main__':
try:
print("publish start...")
rospy.init_node('image_publish', anonymous=True)
image_pub = rospy.Publisher('cam_image', MyImage, queue_size=5)
publish()
rospy.spin()
except rospy.ROSInterruptException:
print('ROSInterruptException')
pass
- 然后节点收到msgs后再转为矩阵显示
import rospy
import cv2
from my_msgs.msg import MyImage
import numpy as np
def callback(datas):
sec = datas.time
image = np.array(list(datas.data), dtype=np.uint8).reshape(datas.size) # 注意转换成list才能转arrar,否者msg默认将uint8识别是bytes
cv2.imshow('image', image)
cv2.waitKey(1)
if __name__ == '__main__':
try:
print("show start...")
rospy.init_node('image_show', anonymous=True)
rospy.Subscriber('image', MyImage, callback, queue_size=5)
rospy.spin()
except rospy.ROSInterruptException:
print('ROSInterruptException')
pass
比较粗糙,只是适合少量图片传输,不追求效率的方案使用(高清图片数据量大,转换耗时)
适合测试使用,大数据图片传输使用cv_bridge转换对应的图片格式效率较高