使用ros订阅图像话题并保存成视频

下载代码后,修改:

  • conda环境
  • 视频保存路径
  • 图像话题

使用:运行后,在终端输入start并回车开始录制,输入stop并回车结束录制。

#!/home/cvpr/anaconda3/envs/ros_py37/bin/python3.7
# -*- coding: utf-8 -*-

"""
订阅图像并保存为视频
"""

import rospy
import cv2
from sensor_msgs.msg import Image
from cv_bridge import CvBridge
 

class VideoRecorder:
    def __init__(self, path):
        self.bridge = CvBridge()
        self.image_sub = rospy.Subscriber('/rgb/image_raw', Image, self.image_callback)
        self.frames = []
        self.recording = False
        self.path = path
 
    def image_callback(self, msg):
        try:
            cv_image = self.bridge.imgmsg_to_cv2(msg, "bgr8")
            if self.recording:
                self.frames.append(cv_image)
        except Exception as e:
            print(e)
 
    def start_recording(self):
        self.frames = []
        self.recording = True

    def stop_recording(self):
        self.recording = False
        if self.frames:
            self.save_video()
 
    def save_video(self):
        height = self.frames[0].shape[0]
        weight = self.frames[0].shape[1]
        fps = 30
        # fourcc = cv.VideoWriter_fourcc('M', 'J', 'P', 'G') 用于avi格式的生成
        fourcc = cv2.VideoWriter_fourcc(*'mp4v')  # 用于mp4格式的生成
        videowriter = cv2.VideoWriter(self.path, fourcc, fps, (weight, height))  # 创建一个写入视频对象
        for img in self.frames:
            videowriter.write(img)

        videowriter.release()
        print('save to', self.path)

if __name__ == '__main__':
    rospy.init_node('video_recorder_node', anonymous=True)
    path = 'new.mp4'
    recorder = VideoRecorder(path)

    try:
        while not rospy.is_shutdown():
            cmd = input("Enter 'start' to begin recording or 'stop' to stop recording: ")
            if cmd == 'start':
                recorder.start_recording()
            elif cmd == 'stop':
                recorder.stop_recording()
    except rospy.ROSInterruptException:
        pass
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值