T265深度图像输出

2023-05-16

1. T265深度图像输出

1.1. 环境依赖

  • T265摄像头
  • python3
  • pip3
  • opencv-python
  • pyrealsense2

1.2. 安装运行环境

安装秘钥

sudo apt-key adv --keyserver keys.gnupg.net --recv-key F6E65AC044F831AC80A06380C8B3A55A6F3EFCDE || sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-key F6E65AC044F831AC80A06380C8B3A55A6F3EFCDE

增加库

sudo add-apt-repository "deb http://realsense-hw-public.s3.amazonaws.com/Debian/apt-repo xenial main" -u

安装驱动

sudo apt-get install librealsense2-dkms
sudo apt-get install librealsense2-utils

安装调试环境

sudo apt-get install librealsense2-dev
sudo apt-get install librealsense2-dbg

安装pip

sudo apt install python3-pip

安装opencv-python

pip install opencv-python

安装pyrealsense2

pip install pyrealsense2

1.3. 获取深度图

新建t265_stereo

vim t265_stereo.py

添加下面代码

#!/usr/bin/python
# -*- coding: utf-8 -*-
## License: Apache 2.0. See LICENSE file in root directory.
## Copyright(c) 2019 Intel Corporation. All Rights Reserved.
# Python 2/3 compatibility
from __future__ import print_function

"""
This example shows how to use T265 intrinsics and extrinsics in OpenCV to
asynchronously compute depth maps from T265 fisheye images on the host.
T265 is not a depth camera and the quality of passive-only depth options will
always be limited compared to (e.g.) the D4XX series cameras. However, T265 does
have two global shutter cameras in a stereo configuration, and in this example
we show how to set up OpenCV to undistort the images and compute stereo depth
from them.
Getting started with python3, OpenCV and T265 on Ubuntu 16.04:
First, set up the virtual enviroment:
$ apt-get install python3-venv  # install python3 built in venv support
$ python3 -m venv py3librs      # create a virtual environment in pylibrs
$ source py3librs/bin/activate  # activate the venv, do this from every terminal
$ pip install opencv-python     # install opencv 4.1 in the venv
$ pip install pyrealsense2      # install librealsense python bindings
Then, for every new terminal:
$ source py3librs/bin/activate  # Activate the virtual environment
$ python3 t265_stereo.py        # Run the example
"""

# First import the library
import pyrealsense2 as rs

# Import OpenCV and numpy
import cv2
import numpy as np
from math import tan, pi

"""
In this section, we will set up the functions that will translate the camera
intrinsics and extrinsics from librealsense into parameters that can be used
with OpenCV.
The T265 uses very wide angle lenses, so the distortion is modeled using a four
parameter distortion model known as Kanalla-Brandt. OpenCV supports this
distortion model in their "fisheye" module, more details can be found here:
https://docs.opencv.org/3.4/db/d58/group__calib3d__fisheye.html
"""

"""
Returns R, T transform from src to dst
"""
def get_extrinsics(src, dst):
    extrinsics = src.get_extrinsics_to(dst)
    R = np.reshape(extrinsics.rotation, [3,3]).T
    T = np.array(extrinsics.translation)
    return (R, T)

"""
Returns a camera matrix K from librealsense intrinsics
"""
def camera_matrix(intrinsics):
    return np.array([[intrinsics.fx,             0, intrinsics.ppx],
                     [            0, intrinsics.fy, intrinsics.ppy],
                     [            0,             0,              1]])

"""
Returns the fisheye distortion from librealsense intrinsics
"""
def fisheye_distortion(intrinsics):
    return np.array(intrinsics.coeffs[:4])

# Set up a mutex to share data between threads 
from threading import Lock
frame_mutex = Lock()
frame_data = {"left"  : None,
              "right" : None,
              "timestamp_ms" : None
              }

"""
This callback is called on a separate thread, so we must use a mutex
to ensure that data is synchronized properly. We should also be
careful not to do much work on this thread to avoid data backing up in the
callback queue.
"""
def callback(frame):
    global frame_data
    if frame.is_frameset():
        frameset = frame.as_frameset()
        f1 = frameset.get_fisheye_frame(1).as_video_frame()
        f2 = frameset.get_fisheye_frame(2).as_video_frame()
        left_data = np.asanyarray(f1.get_data())
        right_data = np.asanyarray(f2.get_data())
        ts = frameset.get_timestamp()
        frame_mutex.acquire()
        frame_data["left"] = left_data
        frame_data["right"] = right_data
        frame_data["timestamp_ms"] = ts
        frame_mutex.release()

# Declare RealSense pipeline, encapsulating the actual device and sensors
pipe = rs.pipeline()

# Build config object and stream everything
cfg = rs.config()

# Start streaming with our callback
pipe.start(cfg, callback)

try:
    # Set up an OpenCV window to visualize the results
    WINDOW_TITLE = 'Realsense'
    cv2.namedWindow(WINDOW_TITLE, cv2.WINDOW_NORMAL)

    # Configure the OpenCV stereo algorithm. See
    # https://docs.opencv.org/3.4/d2/d85/classcv_1_1StereoSGBM.html for a
    # description of the parameters
    window_size = 5
    min_disp = 0
    # must be divisible by 16
    num_disp = 112 - min_disp
    max_disp = min_disp + num_disp
    stereo = cv2.StereoSGBM_create(minDisparity = min_disp,
                                   numDisparities = num_disp,
                                   blockSize = 16,
                                   P1 = 8*3*window_size**2,
                                   P2 = 32*3*window_size**2,
                                   disp12MaxDiff = 1,
                                   uniquenessRatio = 10,
                                   speckleWindowSize = 100,
                                   speckleRange = 32)

    # Retreive the stream and intrinsic properties for both cameras
    profiles = pipe.get_active_profile()
    streams = {"left"  : profiles.get_stream(rs.stream.fisheye, 1).as_video_stream_profile(),
               "right" : profiles.get_stream(rs.stream.fisheye, 2).as_video_stream_profile()}
    intrinsics = {"left"  : streams["left"].get_intrinsics(),
                  "right" : streams["right"].get_intrinsics()}

    # Print information about both cameras
    print("Left camera:",  intrinsics["left"])
    print("Right camera:", intrinsics["right"])

    # Translate the intrinsics from librealsense into OpenCV
    K_left  = camera_matrix(intrinsics["left"])
    D_left  = fisheye_distortion(intrinsics["left"])
    K_right = camera_matrix(intrinsics["right"])
    D_right = fisheye_distortion(intrinsics["right"])
    (width, height) = (intrinsics["left"].width, intrinsics["left"].height)

    # Get the relative extrinsics between the left and right camera
    (R, T) = get_extrinsics(streams["left"], streams["right"])

    # We need to determine what focal length our undistorted images should have
    # in order to set up the camera matrices for initUndistortRectifyMap.  We
    # could use stereoRectify, but here we show how to derive these projection
    # matrices from the calibration and a desired height and field of view

    # We calculate the undistorted focal length:
    #
    #         h
    # -----------------
    #  \      |      /
    #    \    | f  /
    #     \   |   /
    #      \ fov /
    #        \|/
    stereo_fov_rad = 90 * (pi/180)  # 90 degree desired fov
    stereo_height_px = 300          # 300x300 pixel stereo output
    stereo_focal_px = stereo_height_px/2 / tan(stereo_fov_rad/2)

    # We set the left rotation to identity and the right rotation
    # the rotation between the cameras
    R_left = np.eye(3)
    R_right = R

    # The stereo algorithm needs max_disp extra pixels in order to produce valid
    # disparity on the desired output region. This changes the width, but the
    # center of projection should be on the center of the cropped image
    stereo_width_px = stereo_height_px + max_disp
    stereo_size = (stereo_width_px, stereo_height_px)
    stereo_cx = (stereo_height_px - 1)/2 + max_disp
    stereo_cy = (stereo_height_px - 1)/2

    # Construct the left and right projection matrices, the only difference is
    # that the right projection matrix should have a shift along the x axis of
    # baseline*focal_length
    P_left = np.array([[stereo_focal_px, 0, stereo_cx, 0],
                       [0, stereo_focal_px, stereo_cy, 0],
                       [0,               0,         1, 0]])
    P_right = P_left.copy()
    P_right[0][3] = T[0]*stereo_focal_px

    # Construct Q for use with cv2.reprojectImageTo3D. Subtract max_disp from x
    # since we will crop the disparity later
    Q = np.array([[1, 0,       0, -(stereo_cx - max_disp)],
                  [0, 1,       0, -stereo_cy],
                  [0, 0,       0, stereo_focal_px],
                  [0, 0, -1/T[0], 0]])

    # Create an undistortion map for the left and right camera which applies the
    # rectification and undoes the camera distortion. This only has to be done
    # once
    m1type = cv2.CV_32FC1
    (lm1, lm2) = cv2.fisheye.initUndistortRectifyMap(K_left, D_left, R_left, P_left, stereo_size, m1type)
    (rm1, rm2) = cv2.fisheye.initUndistortRectifyMap(K_right, D_right, R_right, P_right, stereo_size, m1type)
    undistort_rectify = {"left"  : (lm1, lm2),
                         "right" : (rm1, rm2)}

    mode = "stack"
    while True:
        # Check if the camera has acquired any frames
        frame_mutex.acquire()
        valid = frame_data["timestamp_ms"] is not None
        frame_mutex.release()

        # If frames are ready to process
        if valid:
            # Hold the mutex only long enough to copy the stereo frames
            frame_mutex.acquire()
            frame_copy = {"left"  : frame_data["left"].copy(),
                          "right" : frame_data["right"].copy()}
            frame_mutex.release()

            # Undistort and crop the center of the frames
            center_undistorted = {"left" : cv2.remap(src = frame_copy["left"],
                                          map1 = undistort_rectify["left"][0],
                                          map2 = undistort_rectify["left"][1],
                                          interpolation = cv2.INTER_LINEAR),
                                  "right" : cv2.remap(src = frame_copy["right"],
                                          map1 = undistort_rectify["right"][0],
                                          map2 = undistort_rectify["right"][1],
                                          interpolation = cv2.INTER_LINEAR)}

            # compute the disparity on the center of the frames and convert it to a pixel disparity (divide by DISP_SCALE=16)
            disparity = stereo.compute(center_undistorted["left"], center_undistorted["right"]).astype(np.float32) / 16.0

            # re-crop just the valid part of the disparity
            disparity = disparity[:,max_disp:]

            # convert disparity to 0-255 and color it
            disp_vis = 255*(disparity - min_disp)/ num_disp
            disp_color = cv2.applyColorMap(cv2.convertScaleAbs(disp_vis,1), cv2.COLORMAP_JET)
            color_image = cv2.cvtColor(center_undistorted["left"][:,max_disp:], cv2.COLOR_GRAY2RGB)

            if mode == "stack":
                cv2.imshow(WINDOW_TITLE, np.hstack((color_image, disp_color)))
            if mode == "overlay":
                ind = disparity >= min_disp
                color_image[ind, 0] = disp_color[ind, 0]
                color_image[ind, 1] = disp_color[ind, 1]
                color_image[ind, 2] = disp_color[ind, 2]
                cv2.imshow(WINDOW_TITLE, color_image)
        key = cv2.waitKey(1)
        if key == ord('s'): mode = "stack"
        if key == ord('o'): mode = "overlay"
        if key == ord('q') or cv2.getWindowProperty(WINDOW_TITLE, cv2.WND_PROP_VISIBLE) < 1:
            break
finally:
    pipe.stop()

运行t265_stereo.py

python3 t265_stereo.py
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

T265深度图像输出 的相关文章

随机推荐

  • linux下mysql的root密码忘记解决方

    1 xff0e 首先确认服务器出于安全的状态 xff0c 也就是没有人能够任意地连接MySQL数据库 因为在重新设置MySQL的root密码的期间 xff0c MySQL数据库完全出于没有密码保护的 状态下 xff0c 其他的用户也可以任意
  • Pandas DataFrame

    http pandas pydata org pandas docs stable api html dataframe 构造函数 方法描述DataFrame data index columns dtype copy 构造数据框 属性和数
  • Apache域名自动指向虚拟主机目录

    用apache做项目时 xff0c 是经常需要在httpd vhost conf文件中配置虚拟主机 xff0c 用于单独的项目 xff0c 每新开一个项目就需要重新加一个配置 xff0c 着实麻烦 xff0c apache2其实是支持在配置
  • CentOS上升级PHP5.3至PHP5.5

    最近想玩玩儿symfony2 发现自己CentOS上的PHP版本还是5 3不符合要求 xff0c 所以想升级至5 5 但是 CentOS通过yum更新的源最新版本是5 3 无法升级 xff0c 通过网上查找资料 发现 更新下yum的源后 可
  • 启动docker web服务时 虚拟机端口转发 外部无法访问

    centos 7 docker 启动了一个web服务 但是启动时 报 WARNING IPv4 forwarding is disabled Networking will not work 网上查询了下 需要做如下配置 解决办法 xff1
  • CentOS7下docker启动报Error starting daemon: Error initializing network controller: could not delete ...v

    前一天晚上强制关闭了虚拟机 CentOS7 导致早上启动docker 报Error starting daemon Error initializing network controller could not delete ve endp
  • 在ubuntu1404下安装PHP AMQP拓展 并进行docker容器封装

    有项目用到过rabbitmq 是技术负责人搭建好环境 xff0c 今天自己在本地 ubuntu 开发 xff0c 重新搞了下 xff0c 在网上查了下资料 xff0c 把安装重点记录下来 项目开发语言PHP 需要与一台rabbitmqser
  • centos7下将docker的storage 由loop-lvm 更改为 direct-lvm

    本机服务器环境是centos7 xff08 vbox虚拟机 xff09 安装docker后 运行正常 xff0c 某次强行关闭了虚拟机 导致后续docker运行不起来 xff0c 发现报错是与storage有关 xff0c 所以网上查原因是
  • ubuntu1604下添加自启动项 开机启动docker开发环境

    在win7下安装的vbox虚拟机 xff0c 虚拟机起了一个ubuntu1604作为宿主机 xff0c 安装的docker服务 通过vbox的挂载工具将win7下的程序开发目录挂载到了ubuntu下 作为共享目录 docker安装的开发环境
  • apache2自签名证书开启ssl

    生成私钥文件 需要输入密码 openssl genrsa des3 out apache key 1024 防止APACHE启动 读取私钥文件也需要输入密码 去除密码输入 openssl rsa in apache key out apac
  • alpine 下编译php5.4的源码报Invalid configuration `x86_64-linux-musl'错误

    Invalid configuration 96 x86 64 linux musl 39 system 96 musl 39 not recognized configure error bin bash 在alpine3 7上编译php
  • golang GRPC安装

    1 下载protoc编译器 https github com protocolbuffers protobuf releases 将protoc exe放到系统环境变量设置的目录下 2 安装golang相关的package go get g
  • reStructuredText

    段落 段落必须由空行代替 段落1 段落2 内联标记 span class hljs emphasis 斜体 span span class hljs strong 粗体 span span class hljs code 96 96 代码块
  • win10下安装kubernets

    win10下安装docker for windows后 xff0c 新版是有一个kubernets选项 xff0c 选择启动后 xff0c 一直报 kubernets is starting 的错误 xff0c 原因是 xff0c kube
  • 嵌入式工程师的自我修养

    文章目录 前言一 认知的四个阶段1 不知不知2 知道不知3 知道己知3 1 软硬件3 2 网络3 3 安全技术 xff08 换成你自己的领域 xff09 3 4 真正知道的三个阶段3 4 1 会用3 4 2 了解怎么实现3 4 3 明白为什
  • 利用uORB机制实现数据在不同进程中通信

    uORB实际上是一种设计模式中的观察者模式 xff0c 用于实现一种一对多的依赖关系 xff0c 让多个观察者 xff08 Observer xff09 同时监听某一主题对象 xff08 Subject xff09 当这个主题对象 xff0
  • Android-注解篇

    1 什么是注解 从JDK 5 开始 xff0c Java 增加了注解 xff0c 注解是代码里的特殊标记 xff0c 这些标记可以在编译 类加载 运 行时被读取 xff0c 并执行相应的处理 通过使用注解 xff0c 开发人员可以在不改变原
  • 新品BCM6755A1KFEBG/MT7921LE/MT7921AU WiFi芯片

    博通在WiFi市场具有相当的实力 在WiFi6上有下面这几个解决方案 xff1a 型号 xff1a BCM6755 BCM6755A1KFEBG 类型 xff1a 四核1 5GHz CPU 封装 xff1a BGA 批次 xff1a 新 B
  • Ubuntu : GPG签名验证错误 解决之道sudo apt-key adv --recv-keys --keyserver keyserver.ubuntu.com 6DFBCBAE

    Ubuntu GPG签名验证错误 解决之道 转载 sudo apt key adv keyserver keyserver ubuntu com recv keys Key Where key 61 61 the gpg key id Th
  • T265深度图像输出

    1 T265深度图像输出 1 1 环境依赖 T265摄像头python3pip3opencv pythonpyrealsense2 1 2 安装运行环境 安装秘钥 span class token function sudo span ap