从搭载orbbec AstraS相机的塔克创新ROS机器人录制的bag包中提取出深度图和彩色图的方法

这是从塔克创新ROS小车录制出的bag包中提取出深度图和RGB图的脚本
塔克创新ROS小车搭载的深度相机型号为奥比中光ASTRAS(比较垃圾)
 

#提取脚本#

extract_rgb_depth.py

# coding:utf-8

import roslib
import rosbag
import rospy
import cv2
from sensor_msgs.msg import Image
from cv_bridge import CvBridge, CvBridgeError
import os
import sys

class ImageCreator:

    def __init__(self, bag_file):
        self.bridge = CvBridge()
        # 修改为相对路径
        rgb_path = os.path.join(os.path.dirname(__file__), 'rgb')
        depth_path = os.path.join(os.path.dirname(__file__), 'depth')
        if not os.path.exists(rgb_path):
            os.makedirs(rgb_path)
        if not os.path.exists(depth_path):
            os.makedirs(depth_path)
        with rosbag.Bag(bag_file, 'r') as bag:  # 要读取的bag文件从参数获取
            for topic, msg, t in bag.read_messages():
                if topic == "/camera/rgb/image_raw":  # RGB图像的topic
                    try:
                        cv_image = self.bridge.imgmsg_to_cv2(msg, "bgr8")
                    except CvBridgeError as e:
                        print(e)
                    timestr = "%.6f" % msg.header.stamp.to_sec()
                    # %.6f表示小数点后带有6位,可根据精确度需要修改
                    image_name = timestr + ".jpg"  # 图像命名:时间戳.jpg
                    cv2.imwrite(os.path.join(rgb_path, image_name), cv_image)  # 保存RGB图像
                elif topic == "/camera/depth/image_raw":  # 灰度图像的topic
                    try:
                        cv_image = self.bridge.imgmsg_to_cv2(msg, "32FC1")
                    except CvBridgeError as e:
                        print(e)
                    timestr = "%.6f" % msg.header.stamp.to_sec()
                    image_name = timestr + ".jpg"  # 图像命名:时间戳.png
                    # 保存灰度图像,这里保存为PNG格式更合适,因为深度值可能是浮点数
                    cv2.imwrite(os.path.join(depth_path, image_name), cv_image * 255.0)  

if __name__ == '__main__':
    if len(sys.argv) != 2:
        print("Usage: python image_creator.py <bag_file>")
        sys.exit(1)
    bag_file = sys.argv[1]
    try:
        image_creator = ImageCreator(bag_file)
    except rospy.ROSInterruptException:
        pass

运行方法 命令行

$ python3 extract_rgb_depth.py name_of_bag.bag 

#图像预处理脚本用来运行ORB-SLAM#

preprocessing

import os

def process_images(folder_path, txt_file_path):
    # 获取文件夹中的所有 .jpg 文件,并按时间戳排序
    jpg_files = [f for f in os.listdir(folder_path) if f.endswith('.jpg')]
    jpg_files.sort(key=lambda x: float(os.path.splitext(x)[0]))

    # 打开txt文件准备写入
    with open(txt_file_path, 'w') as txt_file:
        # 遍历排序后的文件列表
        for filename in jpg_files:
            # 获取文件的基名和扩展名
            base_name = os.path.splitext(filename)[0]

            # 构建新的文件名
            new_filename = base_name + '.png'

            # 获取旧文件和新文件的完整路径
            old_file = os.path.join(folder_path, filename)
            new_file = os.path.join(folder_path, new_filename)

            # 重命名文件
            os.rename(old_file, new_file)

            # 写入txt文件
            txt_file.write(f"{base_name} {folder_path}/{new_filename}\n")

    print(f"处理完成,生成{txt_file_path}文件。")

if __name__ == '__main__':
    # 定义文件夹路径和输出txt文件路径
    depth_folder_path = 'depth'
    rgb_folder_path = 'rgb'
    depth_txt_file_path = 'depth.txt'
    rgb_txt_file_path = 'rgb.txt'

    # 处理深度图像
    process_images(depth_folder_path, depth_txt_file_path)

    # 处理 RGB 图像
    process_images(rgb_folder_path, rgb_txt_file_path)

运行方法 命令行

$ python3 preprocessing.py 

#生成同步时间戳文件associations.txt的脚本#

def merge_files(rgb_file, depth_file, output_file):
    with open(rgb_file, 'r') as rgb_f, open(depth_file, 'r') as depth_f, open(output_file, 'w') as out_f:
        for line in rgb_f:
            out_f.write(line.strip() + ' ')
            depth_line = depth_f.readline().strip()
            out_f.write(depth_line + '\n')

if __name__ == "__main__":
    rgb_file = 'rgb.txt'
    depth_file = 'depth.txt'
    output_file = 'associations.txt'
    merge_files(rgb_file, depth_file, output_file)

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一份基于ROS塔克创新小车红绿灯识别寻线代码,你可以根据需要进行修改: ```python #!/usr/bin/env python # coding:utf-8 import cv2 import numpy as np import rospy from sensor_msgs.msg import Image from cv_bridge import CvBridge, CvBridgeError from std_msgs.msg import String class LineDetector: def __init__(self): rospy.init_node('LineDetector', anonymous=True) self.bridge = CvBridge() self.image_sub = rospy.Subscriber('/camera/color/image_raw', Image, self.callback) self.line_pub = rospy.Publisher('/line_info', String, queue_size=1) def callback(self, data): try: cv_image = self.bridge.imgmsg_to_cv2(data, "bgr8") except CvBridgeError as e: print(e) hsv = cv2.cvtColor(cv_image, cv2.COLOR_BGR2HSV) lower_yellow = np.array([20, 100, 100], dtype=np.uint8) upper_yellow = np.array([30, 255, 255], dtype=np.uint8) mask = cv2.inRange(hsv, lower_yellow, upper_yellow) h, w, d = cv_image.shape search_top = 3*h/4 # 需要寻找线的区域的顶部 search_bot = search_top + 20 # 需要寻找线的区域的底部 mask[0:search_top, 0:w] = 0 mask[search_bot:h, 0:w] = 0 M = cv2.moments(mask) if M['m00'] > 0: cx = int(M['m10']/M['m00']) cy = int(M['m01']/M['m00']) self.line_pub.publish(str(cx) + "," + str(cy)) if __name__ == '__main__': ld = LineDetector() try: rospy.spin() except KeyboardInterrupt: print("Shutting down") ``` ```python #!/usr/bin/env python # coding:utf-8 import cv2 import numpy as np import rospy from sensor_msgs.msg import Image from cv_bridge import CvBridge, CvBridgeError from std_msgs.msg import String class TrafficLightDetector: def __init__(self): rospy.init_node('TrafficLightDetector', anonymous=True) self.bridge = CvBridge() self.image_sub = rospy.Subscriber('/camera/color/image_raw', Image, self.callback) self.light_pub = rospy.Publisher('/traffic_light', String, queue_size=1) def callback(self, data): try: cv_image = self.bridge.imgmsg_to_cv2(data, "bgr8") except CvBridgeError as e: print(e) hsv = cv2.cvtColor(cv_image, cv2.COLOR_BGR2HSV) lower_red = np.array([0, 100, 100], dtype=np.uint8) upper_red = np.array([10, 255, 255], dtype=np.uint8) mask1 = cv2.inRange(hsv, lower_red, upper_red) lower_red = np.array([160, 100, 100], dtype=np.uint8) upper_red = np.array([179, 255, 255], dtype=np.uint8) mask2 = cv2.inRange(hsv, lower_red, upper_red) mask = mask1 + mask2 h, w, d = cv_image.shape search_top = 3*h/4 # 需要寻找交通灯的区域的顶部 search_bot = search_top + 20 # 需要寻找交通灯的区域的底部 mask[0:search_top, 0:w] = 0 mask[search_bot:h, 0:w] = 0 M = cv2.moments(mask) if M['m00'] > 0: cx = int(M['m10']/M['m00']) cy = int(M['m01']/M['m00']) self.light_pub.publish(str(cx) + "," + str(cy)) if __name__ == '__main__': tld = TrafficLightDetector() try: rospy.spin() except KeyboardInterrupt: print("Shutting down") ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值