将视频转换为图片这是大家都熟知的操作,本博文介绍一下将图片转换为视频。下面直接给出代码
#include <ros/ros.h>
#include <iostream>
#include <opencv2/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <image_transport/image_transport.h>
#include <cv_bridge/cv_bridge.h>
#include <opencv2/opencv.hpp>
#include <sstream>
#include <stdlib.h>
#include <stdio.h>
#include <cv.h>
#include "std_msgs/String.h"
using namespace std;
using namespace cv;
cv::Mat img;
int i=0;
char image_name[30];
int isColor = 1;
int frame_fps =60;
int frame_width = 640;
int frame_height = 480;
string video_name = "out.avi";
cv::VideoWriter writer = VideoWriter(video_name, CV_FOURCC('X', 'V', 'I', 'D'),frame_fps,Size(frame_width,frame_height),isColor);
//cv::namedWindow("image to video", CV_WINDOW_AUTOSIZE);
class IMAGE_LISTENER_and_LOCATOR {
private:
ros::NodeHandle nh_; // 定义ROS句柄
image_transport::ImageTransport it_; // 定义一个image_transport实例
image_transport::Subscriber image_sub_; // 定义ROS图象接收器
public:
IMAGE_LISTENER_and_LOCATOR()
:it_(nh_) { // 构造函数
// 定义图象接受器,订阅话题是“camera/image”
image_sub_ = it_.subscribe("camera/image", 1, &IMAGE_LISTENER_and_LOCATOR::convert_callback, this);
// 初始化输入输出窗口
// cv::namedWindow(INPUT);
// cv::namedWindow(OUTPUT);
}
~IMAGE_LISTENER_and_LOCATOR() { // 析构函数
// cv::destroyWindow(INPUT);
// cv::destroyWindow(OUTPUT);
}
void convert_callback(const sensor_msgs::ImageConstPtr& msg)
{
cv_bridge::CvImagePtr cv_ptr; // 声明一个CvImage指针的实例
try {
// 将ROS消息中的图象信息提取,生成新cv类型的图象,复制给CvImage指针
cv_ptr = cv_bridge::toCvCopy(msg, sensor_msgs::image_encodings::MONO8);
}
catch(cv_bridge::Exception& e) { // 异常处理
ROS_ERROR("cv_bridge exception: %s", e.what());
return;
}
img=cv_ptr->image;
sprintf(image_name, "%s%d%s", "/home/song/img/image", ++i, ".jpg");
//resize(img,img,Size(1536,2048));
//imshow("image to video",img);
if (!img.data)//判断图片调入是否成功
{
cout<< "Could not load image file...\n" << endl;
}
cv::imwrite(image_name,img);
img = imread(image_name);
//images.push_back(img);
writer.write(img);
}
};
int main(int argc, char **argv)
{
ros::init(argc, argv, "Get_vedio");
IMAGE_LISTENER_and_LOCATOR obj;
ros::spin();
return 0;
}