本教程将讲述如何用ZED SDK获取深度信息,当获取到50张图片时程序将停止。
创建摄像头
如前例,我们需要先创建初始化摄像头。本例中,我们设置摄像头的分辨率为720,帧速率为60,在PERFORMANCE mode中让深度使能。ZED SDK提供了不同种深度模式:性能、中等、质量。更多信息,可以参考文档。
# Create a ZED camera
zed = sl.Camera()
# Create configuration parameters
init_params = sl.InitParameters()
init_params.sdk_verbose = True # Enable the verbose modeinit_params.depth_mode = sl.DEPTH_MODE.PERFORMANCE
# Set the depth mode to performance (fastest)
# Open the camera
err = zed.open(init_params)
if (err!=sl.ERROR_CODE.SUCCESS)
exit(-1)
注:在实际中,摄像头的深度已经默认设置为PERFORMANCE模式,无需在初始化时重复设置。
获取数据
现在摄像头已经打开了,我们可以获取图片和深度了,在本例中我们将再次循环50次。获取深度地图和获取图片一样简单。
- 首先,我们创建一个sl.Mat类型的数据来存放深度地图
- 然后,通过retrieve_measure()来获取深度地图
# Capture 50 images and depth, then stop
i = 0
image = sl.Mat()
depth = sl.Mat()
point_cloud = sl.Mat()
while (i < 50) :
# Grab an image
if (zed.grab() == sl.ERROR_CODE.SUCCESS) :
# A new image is available if grab() returns SUCCESS
zed.retrieve_image(image, sl.VIEW.LEFT)
# Get the left image
zed.retrieve_measure(depth, sl.MEASURE.DEPTH)
# Retrieve depth Mat. Depth is aligned on the left image
zed.retrieve_measure(point_cloud, sl.MEASURE.XYZRGBA)
# Retrieve colored point cloud. Point cloud is aligned on the left image
i = i + 1
现在我们已经获得了深度地图,我们可能想要获得某一的像素点的深度。在本例中,我们获取图片中央的深度。深度有以下几种:
- DEPTH (Y) 存储类型为:sl.MAT_TYPE.F32_C1
- XYZ (X, Y, Z, not used) 存储类型为:sl.MAT_TYPE.F32_C4 (最后一位表示用32位来存储RGBA信息,解码为usigned char[4])
- XYZABGR (X, Y, Z, color) 存储类型为:sl.MAT_TYPE.F32_C4
# Get and print distance value in mm at the center of the image
# We measure the distance camera - object using Euclidean distance
x = image.get_width() / 2
y = image.get_height() / 2
point_cloud_value = point_cloud.get_value(x, y)[1]
distance = math.sqrt(point_cloud_value[0]*point_cloud_value[0] + point_cloud_value[1]*point_cloud_value[1] + point_cloud_value[2]*point_cloud_value[2])
print("Distance to Camera at (", x, y, "): ", distance, "mm")
当循环50次后,关闭摄像头。
# Close the camera
zed.close()