目录
目的
将相机录制的mp4格式文件,转为ROS系统能使用的bag格式文件。
如果相机的画面不是正视的,会影响后续使用,需要旋转调整。
环境
安装有ROS和python2。
主要步骤
创建py文件
python
# -*- coding: utf-8 -*-
import rosbag
import cv2
from sensor_msgs.msg import CompressedImage
from cv_bridge import CvBridge
import rospy
import numpy as np
def video_to_bag(video_path, output_bag):
bag = rosbag.Bag(output_bag, 'w')
cap = cv2.VideoCapture(video_path)
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 30."
prop_fps = 30
prop_fps = 30
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
# 逆时针时针旋转90度*3
rotated_frame = np.rot90(frame, k=3)
compressed_image = CompressedImage()
compressed_image.header.stamp = stamp + rospy.Duration.from_sec(1701295483.21)
compressed_image.header.frame_id = "camera"
compressed_image.format = "jpeg" # 使用JPEG压缩格式
# 将图像转换为压缩格式
_, compressed_data = cv2.imencode('.jpg', rotated_frame, [int(cv2.IMWRITE_JPEG_QUALITY), 90])
compressed_image.data = compressed_data.tostring()
bag.write("/camera/image_raw/compressed", compressed_image, compressed_image.header.stamp)
bag.close()
cap.release()
# 输入视频文件和输出bag文件名
video_path = 'video2bag.mp4'
output_bag = 'video2bag_time.bag'
# 调用函数进行转换
video_to_bag(video_path, output_bag)
以下参数根据需要,相应的修改:
视频路径video_path
保存的bag文件路径output_bag
图像的话题名,文中是"/camera/image_raw/compressed"
图像的坐标系compressed_image.header.frame_id,文中是"camera"
图像的压缩格式compressed_image.format,文中是"jpeg"
视频帧率prop_fps,文中固定为24,根据需要调整程序。
另外,
旋转角度,根据需要选k为1、2、3个90度。
偏移的时间戳,文中是1701295483.21。
执行py文件
python Video2ROSbag.py
效果
生成bag文件。
查看bag信息:
$rosbag info video2bag_time.bag
path: video2bag_time.bag
version: 2.0
duration: 5.1s
start: Nov 29 2023 22:04:43.21 (1701295483.21)
end: Nov 29 2023 22:04:48.28 (1701295488.28)
size: 8.2 MB
messages: 153
compression: none [11/11 chunks]
types: sensor_msgs/CompressedImage [8f7a12909da2c9d3332d540a0977563f]
topics: /camera/image_raw/compressed 153 msgs : sensor_msgs/CompressedImage
程序解释
画面旋转
使用numpy库,将frame旋转90度,旋转k次:
python
import numpy as np
# 逆时针时针旋转90度*3
rotated_frame = np.rot90(frame, k=3)
时间戳调整
python
compressed_image.header.stamp = stamp + rospy.Duration.from_sec(1701295483.21)
将stamp加上实际时间与1970/1/1的时间差,并将调整时间戳后的compressed_image写进bag。
bag.write("/camera/image_raw/compressed", compressed_image, compressed_image.header.stamp)
参考