前提:已知一组图片和记录该图像路径的txt文件.
通过rosbag::Bag
将指定的一组图像转换成bag的形式
参考链接:https://blog.csdn.net/HelloJinYe/article/details/107350584
最后usleep(100*1000);
控制bag的帧率,100x1000
表示每帧图像之间的间隔为100ms,帧率为10hz
1 imgtobag_new.cpp文件
#include <string>
#include <ros/console.h>
#include <rosbag/bag.h>
#include <cv_bridge/cv_bridge.h>
#include <iostream>
#include <vector>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <unistd.h>
using namespace std;
using namespace cv;
int main(int argc, char **argv)
{
//读取图片和点云信息
vector<string> img_names;
ifstream fin;
string imageDir = "/home/lusx/data/semantic/test/src/data_new.txt";
fin.open(imageDir.c_str());
if(!fin.is_open())
{
cerr<<"imageDir "<<imageDir<<"is wrong."<<endl;
exit(1);
}
while(!fin.eof())
{
string path;
getline(fin, path);
if(!path.empty())
img_names.push_back(path);
}
ros::Time::init();
rosbag::Bag bag;
string output_bag="./res.bag";
bag.open(output_bag, rosbag::bagmode::Write);
int seq = 0;
for(size_t i=0;i<img_names.size();i++)
{
string strImgFile = img_names[i];
// --- for image ---//
cv::Mat img = cv::imread(strImgFile);
if (img.empty())
cout<<"图片为空: "<<strImgFile<<endl;
cv_bridge::CvImage ros_image;
sensor_msgs::ImagePtr ros_image_msg;
ros_image.image = img;
ros_image.encoding = "bgr8";
ros::Time timestamp_ros = ros::Time::now();
ros_image_msg = ros_image.toImageMsg();
ros_image_msg->header.seq = seq;
ros_image_msg->header.stamp = timestamp_ros;
ros_image_msg->header.frame_id = "/image_raw";
bag.write("/cam", timestamp_ros, ros_image_msg);
cout<<"process image["<<i<<"] done."<<endl;
usleep(100*1000);
}
return 0;
}
2 CMakeLists.txt文件
cmake_minimum_required(VERSION 3.2)
project(imagetobag)
find_package(catkin REQUIRED COMPONENTS
roscpp
rospy
rosbag
std_msgs
sensor_msgs
cv_bridge
)
find_package(OpenCV 3 REQUIRED)
catkin_package(
INCLUDE_DIRS
CATKIN_DEPENDS
rosbag
rospy
std_msgs
sensor_msgs
cv_bridge
message_runtime
)
include_directories(${catkin_INCLUDE_DIRS} ${OpenCV_INCLUDE_DIR})
add_executable(imgtobag_new imgtobag_new.cpp)
target_link_libraries(imgtobag_new ${catkin_LIBRARIES} ${OpenCV_LIBS})
3 package.xml文件
<?xml version="1.0"?>
<package>
<name>imagetobag</name>
<version>1.0.0</version>
<description>ROS sample</description>
<maintainer email="lusx@dhsjdhsu.edu">Lusx</maintainer>
<license>TODO</license>
<author>Lusx</author>
<buildtool_depend>catkin</buildtool_depend>
<build_depend>roscpp</build_depend>
<run_depend>roscpp</run_depend>
<build_depend>rospy</build_depend>
<run_depend>rospy</run_depend>
<build_depend>rosbag</build_depend>
<run_depend>rosbag</run_depend>
<build_depend>cv_bridge</build_depend>
<run_depend>cv_bridge</run_depend>
<build_depend>std_msgs</build_depend>
<run_depend>std_msgs</run_depend>
<build_depend>sensor_msgs</build_depend>
<run_depend>sensor_msgs</run_depend>
<build_depend>message_generation</build_depend>
<run_depend>message_generation</run_depend>
<build_depend>message_runtime</build_depend>
<run_depend>message_runtime</run_depend>
</package>