深度相機的圖像深度實時顯示

最近有了一個intel 的 D435i 深度相機,網上找了一個實時顯示圖片和深度圖的python 程序,最開始是一個博客,後來發現在intel 的github裏也有。都找不到鏈接了,覺得不錯,修改整理成本文。

首先要安裝好pyrealsense2 ,鏈接是: realsense.intel.com/get-started

官網提供的軟件工具與文檔資料介紹
https://realsense.intel.com/intel-realsense-downloads/#firmware
1、Intel RealSense Viewer.exe 是最主要的軟件,功能是查看查看視頻流,並可以對視頻流進行後期處理,這個官方GitHub有提供完整的c++工程,編譯了可以直接運行;
2、Depth Quality Tool for Intel RealSense Cameras.exe 用於測試z方向的深度數據是否準,只需要把rgbd相機正對着白色的牆面等就可以了,然後對比捲尺量的距離與軟件上顯示的距離,來判斷是否需要校準相機;
3、Intel RealSense D400 Series Dynamic Calibration Software Tools這個是校準工具,如果前面計算的距離不準,可以利用這個軟件進行校準,在蘋果或安卓手機搜realsense這個軟件,安裝打開,就是顯示一張類似棋盤格標定板的圖片,然後配合校準工具,按照上面的提示晃動手機即可校準,輸出外參R\T。

下面是實時顯示圖像和深度的python 代碼:

請注意,深度是轉換成圖片顯示的。

import pyrealsense2 as rs
import numpy as np
import cv2

# 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)
try:
    while True:
        # Wait for a coherent pair of frames: depth and color
        frames = pipeline.wait_for_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())

        # Apply colormap on depth image (image must be converted to 8-bit per pixel first)
        depth_colormap = cv2.applyColorMap(cv2.convertScaleAbs(depth_image, alpha=0.03), cv2.COLORMAP_JET)
        # Stack both images horizontally
        images = np.hstack((color_image, depth_colormap))
        # Show images
        cv2.namedWindow('RealSense', cv2.WINDOW_AUTOSIZE)
        cv2.imshow('RealSense', images)
        key = cv2.waitKey(1)
        # Press esc or 'q' to close the image window
        if key & 0xFF == ord('q') or key == 27:
            cv2.destroyAllWindows()
            break
        elif key & 0xFF == ord('s'):
            cv2.imwrite('savefile.jpg',images)
finally:
    # Stop streaming
    pipeline.stop()

運行的效果如下(左邊,圖片,右邊,深度圖片):

如何把這2張圖片轉換爲3D呢?

首先把這2張圖片,分別存在各自的一個文件裏,然後參考我的另一博文: 使用opencv以及pcl將2D圖像轉換爲3D點雲

如何檢測圖中物體的深度或者座標呢?

先要了解相機的基本參數如下(我上文c++代碼):

// 相機內參,這個參數不是D435i 的,僅僅做個參考
const double camera_factor = 1000;
const double camera_cx = 325.5;
const double camera_cy = 253.5;
const double camera_fx = 518.0;
const double camera_fy = 519.0;

然後呢,就可以計算了(我上文c++代碼):

// 獲取深度圖中(m,n)處的值
ushort d = depth.ptr<ushort>(m)[n];
// d 可能沒有值,若如此,跳過此點
if (d == 0)continue; //說明這點沒有深度值

// 計算這個點的空間座標
p.z = double(d) / camera_factor;
p.x = (n - camera_cx) * p.z / camera_fx;
p.y = (m - camera_cy) * p.z / camera_fy;

也可以參考 https://github.com/IntelRealSense/librealsense/blob/jupyter/notebooks/distance_to_object.ipynb

或者等待我的下一個博客。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章