前言
工作中遇到域控中无中间件,无法采用rosbag等中间件的形式同时采集感知结果与视频流,只能通过外接摄像头采集视频流,以及使用can报文或者bin文件形式存储路测数据;导致本地回放时,无法通过视频流观察真实情况,来判断优化方向。于是,另辟蹊径,将工程代码转成ros方式以及将视频流转成rosbag,可同时使用rviz分析算法与image定位问题;
注意事项
1.需要使用python2
代码
import time, sys, os
from ros import rosbag
import roslib, rospy
roslib.load_manifest('sensor_msgs')
from sensor_msgs.msg import Image
import argparse
from cv_bridge import CvBridge
import cv2
TOPIC = "/image_viz" # 对应topic_name
def CreateVideoBag(videopath, bagname):
'''Creates a bag file with a video file'''
print("raw mp4 name:",videopath)
print("output bag name:",bagname)
bag = rosbag.Bag(bagname, 'w')
cap = cv2.VideoCapture(videopath)
cb = CvBridge()
prop_fps = cap.get(cv2.CAP_PROP_FPS)
if prop_fps != prop_fps or prop_fps <= 1e-2:
print("Warning: can't get FPS. Assuming 24.")
prop_fps = 24
prop_fps = 24 #
print("set fps:",prop_fps)
ret = True
frame_id = 0
while(ret):
ret, frame = cap.read()
if not ret:
break
stamp = rospy.rostime.Time.from_sec(float(frame_id) / prop_fps)
frame_id += 1
image = cb.cv2_to_imgmsg(frame, encoding='bgr8')
image.header.stamp = stamp
image.header.frame_id = "base_link"
bag.write(TOPIC, image, stamp)
cap.release()
bag.close()
if __name__ == "__main__":
# parser = argparse.ArgumentParser()
# parser.add_argument("--topic", type=str, default="/image_viz")
# args = parser.parse_args()
if len( sys.argv ) == 3:
CreateVideoBag(*sys.argv[1:])
else:
print( "Usage: video2bag videofilename bagfilename")
步骤
python2 mp4_to_bag.py <video_name>.mp4 <output_bag_name>.bag # 执行转化命令
rosbag play -l <output_bag_name>.bag camera/image_raw:=image_raw0 # 循环播放图片,并重命名成自己需要的话题名
结果
PS:请注意视频流与算法处理存在些许的时间差。