§ 2.6 深度图获取与动态更新

1. 导入依赖

# - 矩阵运算
import numpy as np
# - 图像处理
import cv2 
# - 绘图可视化
from matplotlib import pyplot as plt

# 自定义库
# 从阿凯机器人工具箱导入Astra类
from kyle_robot_toolbox.camera import Astra

2. 相机初始化

可以配置图像对齐 image_registration 开关。

# 是否获取对齐后的深度图
# - True :   获取彩色相机坐标系下的深度图
# - False :  获取IR相机坐标系下的深度图
image_registration = True

# 创建相机对象
# config_path要写的是Astra 3D相机的配置文件夹路径
camera = Astra(config_path="../astra-config/config/")
# 初始相机视频流
camera.init_video_stream(video_mode="depth", image_registration=image_registration)

# 读取相机参数(相机内参)
camera.load_cam_calib_data()

3. 获取深度图

# 采集深度图, 单位为mm
# 数据格式为np.float32
depth_img = camera.read_depth_img() 

4. 显示深度图

用灰度表达远近,最远处为白色,最近为黑色。

# 使用灰度图展示深度图
plt.imshow(depth_img,  cmap="gray")

# 保存图像
plt.savefig("data/read_depth_image/gray.png")

将深度图转换为彩色的可视化图:

# 将深度图转换为彩图,进行可视化
# 可以指定最近距离跟最远距离, 单位mm
canvas = camera.depth_img2canvas(depth_img, min_distance=300, max_distance=600)
plt.imshow(canvas[:, :, ::-1])

# 保存图像
plt.savefig("data/read_depth_image/canvas.png")

5. 保存深度图

深度图本身是Numpy的 np.float32 格式。将深度图保存为二进制文件:

# 深度图像保存路径
depth_img_path = "data/read_depth_image/demo.npy"
# 以二进制格式保存Numpy对象
np.save(depth_img_path, depth_img)

image-20220911235203332

6. 读取深度图

# 深度图像保存路径
depth_img_path = "data/read_depth_image/demo.npy"
# 图像保存
depth_img2 = np.load(depth_img_path)

if depth_img2 is None:
    print("深度图读取失败")
else:
    print("深度图读取成功")
# 将深度图转换为彩图,进行可视化
canvas = camera.depth_img2canvas(depth_img2)
plt.imshow(canvas[:, :, ::-1])

7. 深度图动态刷新

在终端里面运行深度图动态刷新的示例代码:

python read_depth_img.py

image-20220912000010276

read_depth_img.py

'''
Astra 3D相机 - 测试深度图读取与动态更新
----------------------------------------------
@作者: 阿凯爱玩机器人
@QQ: 244561792
@微信: xingshunkai
@邮箱: xingshunkai@qq.com
@网址: deepsenserobot.com
@B站: "阿凯爱玩机器人"
'''
# - 矩阵运算
import numpy as np
# - 图像处理
import cv2 
# - Open3D点云处理
import open3d as o3d
# - 绘图可视化
from matplotlib import pyplot as plt

# 自定义库
# 从阿凯机器人工具箱导入Astra类
from kyle_robot_toolbox.camera import Astra

# 配置项
# - 图像对齐
image_registration = False

# 创建相机对象
# config_path要写的是Astra 3D相机的配置文件夹路径
camera = Astra(config_path="../astra-config/config/")

try:
	# 初始相机视频流
	camera.init_video_stream(video_mode="depth", \
     	image_registration=image_registration)
except Exception as e:
	print("[错误] 没有发现Astra设备, 请检查接线或驱动")
	exit(-1)

# 创建窗口
win_flag = cv2.WINDOW_NORMAL | cv2.WINDOW_KEEPRATIO | cv2.WINDOW_GUI_EXPANDED
cv2.namedWindow("depth", flags=win_flag)

while True:
	# 采集深度图
	depth_img = camera.read_depth_img() 
	# 将深度图转换为画布
	canvas = camera.depth_img2canvas(depth_img)
	# 显示图像
	cv2.imshow('depth', canvas)
	key = cv2.waitKey(1)
	if key == ord('q'):
		# 如果按键为q 代表quit 退出程序
		break

# 关闭摄像头
camera.release()
# 销毁所有的窗口
cv2.destroyAllWindows()