Intel RealSense D435i深度相机(Python)

 一、利用深度相机实时测距

代码一(实时显示窗口中心点处的距离信息):

# distance_center
import pyrealsense2 as rs
import numpy as np
import cv2

# 初始化深度相机
pipeline = rs.pipeline()
config = rs.config()
config.enable_stream(rs.stream.depth, 640, 480, rs.format.z16, 30)
config.enable_stream(rs.stream.color, 640, 480, rs.format.bgr8, 30)

pipeline.start(config)

try:
    while True:
        try:
            # 等待深度数据帧和RGB数据帧,设置等待时间为10秒
            frames = pipeline.wait_for_frames(timeout_ms=10000)
            depth_frame = frames.get_depth_frame()
            color_frame = frames.get_color_frame()

            if not depth_frame or not color_frame:
                continue

            # 获取深度图像的原始数据
            depth_data = np.asanyarray(depth_frame.get_data())

            # 获取RGB图像的原始数据
            color_data = np.asanyarray(color_frame.get_data())

            # 在深度图像上叠加距离信息
            depth_value = depth_frame.get_distance(320, 240)  # 320, 240是图像中心像素坐标
            distance_in_meters = round(depth_value, 2)
            cv2.putText(color_data, f"Distance: {distance_in_meters} m", (10, 30),
                        cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)

            # 在图像中心上点上加上标记
            center_x, center_y = 320, 240  # 图像中心像素坐标
            cv2.drawMarker(color_data, (center_x, center_y), (0, 255, 0), cv2.MARKER_CROSS, markerSize=20, thickness=2)

            # 使用伪彩色映射器将深度数据转换为伪彩色图像
            colorizer = rs.colorizer()
            depth_colormap = np.asanyarray(colorizer.colorize(depth_frame).get_data())

            # 创建一个窗口,显示彩色图像和伪彩色深度图像
            combined_image = np.hstack((color_data, depth_colormap))
            cv2.imshow("Combined Image", combined_image)

            # 按Esc键退出循环
            key = cv2.waitKey(1)
            if key == 27:
                break
        except RuntimeError as e:
            print(f"等待帧时发生错误: {e}")

finally:
    pipeline.stop()
    cv2.destroyAllWindows()

代码二(实时显示鼠标点击出的距离信息,实时窗口和终端都显示):

import pyrealsense2 as rs
import numpy as np
import cv2

# 初始化深度相机
pipeline = rs.pipeline()
config = rs.config()
config.enable_stream(rs.stream.depth, 640, 480, rs.format.z16, 30)
config.enable_stream(rs.stream.color, 640, 480, rs.format.bgr8, 30)
pipeline.start(config)

# 创建深度图像的伪彩色映射器
colorizer = rs.colorizer()

# 回调函数,处理鼠标点击事件
def on_mouse_click(event, x, y, flags, param):
    if event == cv2.EVENT_LBUTTONDOWN:  # 当左键被点击时
        distance = depth_frame.get_distance(x, y)  # 获取鼠标点击点的距离
        distance_in_meters = round(distance, 2)
        cv2.putText(combined_image, f"Distance: {distance_in_meters} m", (20, 30),
                    cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)
        print(f"Distance at ({x}, {y}): {distance_in_meters}m")  # 打印距离信息到终端
        cv2.imshow("Combined Image", combined_image)
        cv2.waitKey(100)   # 显示距离文本的时间

# 创建一个窗口并设置鼠标回调函数
cv2.namedWindow("Combined Image")
cv2.setMouseCallback("Combined Image", on_mouse_click)

try:
    while True:
        try:
            # 等待深度数据帧和RGB数据帧,设置等待时间为10秒
            frames = pipeline.wait_for_frames(timeout_ms=10000)
            depth_frame = frames.get_depth_frame()
            color_frame = frames.get_color_frame()

            if not depth_frame or not color_frame:
                continue

            color_data = np.asanyarray(color_frame.get_data())

            depth_colormap = np.asanyarray(colorizer.colorize(depth_frame).get_data())

            combined_image = np.hstack((color_data, depth_colormap))
            cv2.imshow("Combined Image", combined_image)

            key = cv2.waitKey(1)
            if key == 27:
                break
        except RuntimeError as e:
            print(f"等待帧时发生错误: {e}")

finally:
    pipeline.stop()
    cv2.destroyAllWindows()

二、深度相机保存左目和右目图像

import pyrealsense2 as rs
import numpy as np
import cv2
import os
import time

def get_color_images(left_save_dir, right_save_dir):
    # 创建左目和右目的保存路径
    if not os.path.exists(left_save_dir):
        os.makedirs(left_save_dir)
    if not os.path.exists(right_save_dir):
        os.makedirs(right_save_dir)

    # 配置和启动Realsense流
    pipeline = rs.pipeline()
    config = rs.config()
    config.enable_stream(rs.stream.color, 640, 480, rs.format.bgr8, 30)  # 配置彩色流
    pipeline.start(config)

    try:
        while True:
            # 获取图像
            frames = pipeline.wait_for_frames()
            color_frame = frames.get_color_frame()

            # 将图像数据转换为OpenCV格式
            color_image = None
            if color_frame:
                color_image = np.asanyarray(color_frame.get_data())

                # 获取当前时间戳
                t = time.time()
                tname = str(t)[5:10]  # 提取时间的秒数作为时间戳的名称

                # 保存图像到左目和右目的不同文件夹,使用不同的文件名
                left_image_name = 'left_color_image' + str(tname) + '.png'
                right_image_name = 'right_color_image' + str(tname) + '.png'

                cv2.imwrite(os.path.join(left_save_dir, left_image_name), color_image)  # 保存左目彩色图像
                cv2.imwrite(os.path.join(right_save_dir, right_image_name), color_image)  # 保存右目彩色图像

                # 实时显示彩色图像
                cv2.imshow('RealSense Color Image', color_image)

            # 等待1毫秒并检查是否按下Esc键
            key = cv2.waitKey(1)
            if key == 27:  # 27是Esc键的ASCII码
                break

    finally:
        # 停止数据流并销毁窗口
        pipeline.stop()
        cv2.destroyAllWindows()

if __name__ == "__main__":
    left_save_dir = r"left_folder_path"  # 保存左目彩色图像的文件夹路径
    right_save_dir = r"right_folder_path"  # 保存右目彩色图像的文件夹路径

    get_color_images(left_save_dir, right_save_dir)  # 获取并保存彩色图像

  • 4
    点赞
  • 49
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论
【资源说明】 1、该资源包括项目的全部源码,下载可以直接使用! 2、本项目适合作为计算机、数学、电子信息等专业的课程设计、期末大作业和毕设项目,作为参考资料学习借鉴。 3、本资源作为“参考资料”如果需要实现其他功能,需要能看懂代码,并且热爱钻研,自行调试。 基于YOLOv5+Intel_Realsense_D435i开发的物体之间三维距离测量python源码+项目说明.zip 结合YOLOv5对Intel_Realsense_D435i 进行开发,实现实时检测物体之间的三维距离 [yolov5]:实时目标检测算法 [Intel Relsense D435i深度摄像头](https://www.intelrealsense.com/zh-hans/depth-camera-d435i/):Intel使用realsense(实感)技术开发出来的的深度摄像头,可以获取目标的三维信息 ## 1.Use and Environment: 如果您想直接使用,请使用yolov5_D435i_2.0 yolov5_D435i_1.0是本人学习时的版本。 ### Environment: 1.一个可运行yolov5的环境 2.一个Intel realsense D435i相机,pyrealsense2和各种依赖库 ``` 1. could run yolov5 2. pip install -r requirements.txt 3. pip install pyrealsense2 ``` ### Use: 配置yolov5_D435i_2.0/config/yolov5s.yaml,运行yolov5_D435i_2.0/config/main2.py即可 yolov5_D435i_2.0/config/yolov5s.yaml: ``` weight: "weights/yolov5s.pt" # 输入图像的尺寸 input_size: [640,480] # 类别个数 class_num: 80 # 标签名称 class_name: [ 'person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train', 'truck', 'boat', 'traffic light', 'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', 'cow', 'elephant', 'bear', 'zebra', 'giraffe', 'backpack', 'umbrella', 'handbag', 'tie', 'suitcase', 'frisbee', 'skis', 'snowboard', 'sports ball', 'kite', 'baseball bat', 'baseball glove', 'skateboard', 'surfboard', 'tennis racket', 'bottle', 'wine glass', 'cup', 'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple', 'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza', 'donut', 'cake', 'chair', 'couch', 'potted plant', 'bed', 'dining table', 'toilet', 'tv', 'laptop', 'mouse', 'remote', 'keyboard', 'cell phone', 'microwave', 'oven', 'toaster', 'sink', 'refrigerator', 'book', 'clock', 'vase', 'scissors', 'teddy bear', 'hair drier', 'toothbrush' ] # 阈值设置 threshold: iou: 0.45 confidence: 0.6 # 计算设备 # - cpu # - 0 <- 使用GPU device: '0' target: ['person']#检测哪些类别之间的距离 which objects you want to detect ``` ## 2.Attenion ...
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

我本將心向明月

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值