首先根据下面这个文件,修改相应的参数,与自己的摄像头地址,制作topic并发布,使用python编译器运行这个文件
python3 xxx.py
#!/usr/bin/env python
import sys
import cv2
import rospy
from sensor_msgs.msg import Image
from cv_bridge import CvBridge
import os
import numpy as np
def read_cam():
cap = cv2.VideoCapture("v4l2src device=/dev/video0 ! video/x-raw, width=640, height=512 ! videoconvert ! video/x-raw,format=BGR ! appsink")
if cap.isOpened():
while True:
ret_val, img = cap.read()
# print(ret_val, img)
else:
print("camera open failed")
def videocapture():
cap=cv2.VideoCapture("v4l2src device=/dev/video0 ! video/x-raw, width=640, height=512 ! videoconvert ! video/x-raw,format=BGR ! appsink") #生成读取摄像头对象
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) #获取视频的宽度
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) #获取视频的高度
fps = cap.get(cv2.CAP_PROP_FPS) #获取视频的帧率
fourcc = int(cap.get(cv2.CAP_PROP_FOURCC)) #视频的编码
print(fourcc)
#定义视频对象输出
writer = cv2.VideoWriter("video_result.mp4", fourcc, fps, (width, height))
while cap.isOpened():
ret, frame = cap.read() #读取摄像头画面
cv2.imshow('teswell', frame) #显示画面
key = cv2.waitKey(24)
writer.write(frame) #视频保存
# 按Q退出
if key == ord('q'):
break
cap.release() #释放摄像头
cv2.destroyAllWindows() #释放所有显示图像窗口
class ImagePublisher(object):
def __init__(self):
# self.image = None
self.br = CvBridge()
# Node cycle rate (in Hz)
self.loop_rate = rospy.Rate(20)
# Publishers
image_topic = rospy.get_param("~topic_name","image_IR")# the topic name is defined in the private namespace
self.pub = rospy.Publisher(image_topic,Image,queue_size=1) # always publish the latest
# video device to capture
self.device_type = rospy.get_param("~device_type","GMSL")
self.device = rospy.get_param("~device",'/dev/video0') # get the device
self.width = rospy.get_param("~width",'640')
self.height = rospy.get_param("~height",'512')
self.fps = rospy.get_param("~fps",'30')
self.frame_id = rospy.get_param("~frame_id","camera_link_0")
self.to_push_stream = rospy.get_param("~to_push_stream","True")
self.cap = cv2.VideoCapture("v4l2src device=/dev/video0 ! video/x-raw, width=640, height=512 ! videoconvert ! video/x-raw,format=BGR ! appsink") #生成读取摄像头对象
def run(self):
while not rospy.is_shutdown():
ret, frame = self.cap.read()
now = rospy.get_rostime()
if ret:
image_msg = self.br.cv2_to_imgmsg(frame)
image_msg.header.stamp.secs = now.secs
image_msg.header.stamp.nsecs = now.nsecs
image_msg.header.frame_id = self.frame_id
self.pub.publish(image_msg)
else:
break
self.loop_rate.sleep()
self.cap.release()
if __name__ == '__main__':
rospy.init_node("image_publisher",anonymous=True)
publisher = ImagePublisher()
publisher.run()
使用以下命令录制数据:
rosbag record -o xxx /**1 /**2
xxx为希望保存话题的路径和名字
/**1 /**2 为希望录制的话题
但是这种情况很有可能出现以下错误
rosbag record buffer exceeded. Dropping oldest queued message
即录制的话题数太多了,处理器处理不过来,因此我们可以参考一下链接解决
http://wiki.ros.org/rosbag/Commandline#record
我的处理命令是:
resbag record -O xxx -b 4096 /**1 /**2
这样就会增大我的缓存空间,减少丢帧的可能