录制mp4 rospy
ros 预览摄像头
#!/usr/bin/env python
import rospy
from sensor_msgs.msg import Image
from cv_bridge import CvBridge
import cv2# 初始化 bridge
bridge = CvBridge()def image_callback(msg):# 将ROS图像消息转换为OpenCV图像cv_image = bridge.imgmsg_to_cv2(msg, desired_encoding='bgr8')# 显示图像cv2.imshow("Camera View", cv_image)cv2.waitKey(1)if __name__ == '__main__':rospy.init_node('camera_viewer', anonymous=True)# 订阅图像话题//rospy.Subscriber('/camera_l/color/image_raw', Image, image_callback)rospy.Subscriber('/camera_f/color/image_raw', Image, image_callback)rospy.spin()cv2.destroyAllWindows()
view2.py
#!/usr/bin/env python
import rospy
from sensor_msgs.msg import Image
from cv_bridge import CvBridge
import cv2import imageio
import os
import sys
current_dir = os.path.dirname(os.path.abspath(__file__))
current_dir_p=os.path.dirname(current_dir)
os.chdir(current_dir)
print('current_dir',current_dir)
paths = [current_dir,current_dir_p]
paths.append(os.path.join(current_dir, 'src'))for path in paths:sys.path.insert(0, path)os.environ['PYTHONPATH'] = (os.environ.get('PYTHONPATH', '') + ':' + path).strip(':')import time
class Time_Str:def __init__(self):self.last_time = ''self.counter = 0def get_time_sec(self):now_time = time.strftime("%m%d_%H%M_%S") # 当前时间(精确到秒)self.counter += 1if now_time != self.last_time:self.last_time = now_timeself.counter = 0return f"{now_time}_{self.counter}"def get_time_mm(self):now_time = time.strftime("%m%d_%H%M") # 当前时间(精确到秒)self.counter += 1if now_time != self.last_time:self.last_time = now_timeself.counter = 0return f"{now_time}_{self.counter}"# 初始化 bridge
bridge = CvBridge()time_str=Time_Str()
imgs = []
fps = 30
index = 0
count = 0
strat_record = Falseos.makedirs('record',exist_ok=True)def image_callback(msg):global strat_record,count,imgs,index# 将ROS图像消息转换为OpenCV图像cv_image = bridge.imgmsg_to_cv2(msg, desired_encoding='bgr8')img = cv2.cvtColor(cv_image, cv2.COLOR_BGR2RGB)if strat_record:imgs.append(img)index += 1if index % 300 == 299 and strat_record:count += 1save_video_path = f'record/{time_str.get_time_mm()}.mp4'imageio.mimsave(save_video_path, imgs, fps=fps, macro_block_size=None)imgs = []# 显示图像cv2.imshow("Camera View", cv_image)key = cv2.waitKey(1) & 0xFFif key == ord('q'):returnelif key == ord('s'):strat_record = True print("start_record")elif key == ord('e'):strat_record = Falsesave_video_path = f'record/{time_str.get_time_mm()}.mp4'imageio.mimsave(save_video_path, imgs, fps=fps, macro_block_size=None)imgs = []print("end_record")if __name__ == '__main__':rospy.init_node('camera_viewer', anonymous=True)# 订阅图像话题# rospy.Subscriber('/camera_r/color/image_raw', Image, image_callback)rospy.Subscriber('/camera_f/color/image_raw', Image, image_callback)rospy.spin()cv2.destroyAllWindows()