Realsense-python——获取RGB图、深度图并实现可视化和单点测距

34 篇文章 12 订阅

本文采用的相机是Intel Realsense D435i。

对齐深度图和RGB图并可视化深度图

需要注意的是,采用该方法实现后,程序执行的帧率只有3帧/s,所以不推荐在实际使用该方法进行可视化。

depth_img_show.py

import pyrealsense2 as rs
import numpy as np
import cv2

def show_colorizer_depth_img():
    colorizer = rs.colorizer()
    hole_filling = rs.hole_filling_filter()
    filled_depth = hole_filling.process(depth_frame)
    colorized_depth = np.asanyarray(colorizer.colorize(filled_depth).get_data())
    cv2.imshow('filled depth',colorized_depth)


if __name__ == "__main__":
    # Configure depth and color streams
    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)
    # Start streaming
    pipeline.start(config)
    #深度图像向彩色对齐
    align_to_color=rs.align(rs.stream.color)
 
    try:
        while True:
            # Wait for a coherent pair of frames: depth and color
            frames = pipeline.wait_for_frames()
            
            frames = align_to_color.process(frames)
 
            depth_frame = frames.get_depth_frame()
            color_frame = frames.get_color_frame()
            if not depth_frame or not color_frame:
                continue
            # Convert images to numpy arrays
            depth_image = np.asanyarray(depth_frame.get_data())
            color_image = np.asanyarray(color_frame.get_data())

            show_colorizer_depth_img()

            # Press esc or 'q' to close the image window
            key = cv2.waitKey(1)
            if key & 0xFF == ord('q') or key == 27:
                cv2.destroyAllWindows()
                break
    finally:
        # Stop streaming
        pipeline.stop()

获取某点的深度距离

该方法可以用来探测目标物体的距离。
depth_measure.py

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

def get_center_depth(depth):
    # Get the depth frame's dimensions
    width = depth.get_width()
    height = depth.get_height()

    center_x = int(width / 2)
    center_y = int(height / 2)

    print(width, " ", height)
    dis_center = round(depth.get_distance(center_x, center_y)*100, 2)
    print("The camera is facing an object ", dis_center, " cm away.")
    return dis_center, (center_x, center_y)

if __name__ == '__main__':
    # Configure depth and color streams
    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)
    # Configure and start the pipeline
    pipeline.start(config)

    while True:
        start = time.time()
        # Block program until frames arrive
        frames = pipeline.wait_for_frames()

        # RGB image
        color_frame = frames.get_color_frame()
        color_image = np.asanyarray(color_frame.get_data())
        # depth image
        depth = frames.get_depth_frame()
        dis_center, center_coordinate = get_center_depth(depth)

        print("color_image:", color_image.shape)
        cv2.circle(color_image, center_coordinate, 5, (0,0,255), 0)
        cv2.imshow("color_image", color_image)
        
        print("FPS:", 1/(time.time()-start), "/s")

        # press Esc to stop
        k = cv2.waitKey(5) & 0xFF
        if k == 27:
            break

    cv2.destroyAllWindows()

参考文章:

  • 7
    点赞
  • 98
    收藏
    觉得还不错? 一键收藏
  • 9
    评论
获取深度图的方法: 首先,需要使用深度学习模型来预测像的深度信息。可以使用现有的深度学习框架,例如 TensorFlow 或 PyTorch,来训练一个深度学习模型。这个模型需要输入一张片,输出对应的深度图。 以下是一个使用 PyTorch 实现获取深度图的例子: ```python import torch import torchvision.transforms as transforms from PIL import Image # 加载深度学习模型 model = torch.load('depth_prediction_model.pth') # 加载片 img = Image.open('test.jpg') # 对片进行预处理 transform = transforms.Compose([ transforms.Resize((256, 256)), transforms.ToTensor(), transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) ]) img_tensor = transform(img) img_tensor = img_tensor.unsqueeze(0) # 预测深度图 with torch.no_grad(): depth_map = model(img_tensor) # 将深度图转换为 numpy 数组 depth_map = depth_map.squeeze().cpu().numpy() # 显示深度图 import matplotlib.pyplot as plt plt.imshow(depth_map, cmap='gray') plt.show() ``` 上述代码中,我们首先加载了一个深度学习模型,然后使用 PyTorch 的 transforms 对片进行预处理,最后将预处理后的片输入到模型中进行预测。预测的结果是一个深度图,我们将其转换为 numpy 数组并显示出来。 根据单目进行测距的方法: 根据单目进行测距的方法主要有两种:三角化法和尺度恢复法。 三角化法基于两个相机的视差信息计算出物体的深度,需要知道两个相机的内参和外参。因为需要两个相机,所以这种方法比较复杂。 尺度恢复法则是根据物体的大小和相机的视角计算出物体的深度。这种方法只需要一个相机,但需要知道物体的大小。可以使用物体的实际大小或者通过其他途径获得物体大小的估计值。 以下是一个使用尺度恢复法进行测距的例子: ```python # 获得深度图中的某个像素的深度值 depth = depth_map[100, 100] # 计算物体的实际大小 object_size = 0.2 # 假设物体的实际大小为 20 厘米 # 计算相机的视角 fov = 60 # 假设相机的视角为 60 度 img_width, img_height = img.size focal_length = img_width / (2 * np.tan(np.deg2rad(fov) / 2)) # 计算距离 distance = object_size * focal_length / depth print('距离为:', distance, '米') ``` 上述代码中,我们首先获得深度图中某个像素的深度值,然后计算物体的实际大小。接下来,我们计算相机的视角,并根据相机的视角和像宽度计算出相机的焦距。最后,我们使用尺度恢复法计算出距离。需要注意的是,这种方法只是一个估计值,因为物体的大小可能不是完全准确的。
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值