加快深度图像到点云的转换 (Python)

Speeding up depth image to point-cloud conversion (Python)

我目前正在尝试加快 python 中从深度到点云的转换。目前代码如下所示:

   color_points = []
   for v in range(depth.shape[1]):
        for u in range(depth.shape[0]):
            z = depth[u,v] / self.scaling_factor
            if z == 0:   # here np.where can be used prior to the loop
                continue
            x = (u - self.center_x) * z / self.focalLength     # u and v are needed, no clue how to do this
            y = (v - self.center_y) * z / self.focalLength

            color_points.append([x, y, z])

我的主要问题是,我不知道有任何函数(如 np.where)可以加速图像数组的循环,同时仍然具有像素索引(例如 u 和 v ).需要索引,因为计算取决于像素在传感器上的位置。

Cython 将是加速它的一个选项,但我仍然认为 NumPy 中必须有更好的功能可用。

感谢您的帮助!

编辑:在函数中添加了 Z 计算。比例因子取决于您获得深度图像的格式。在我的例子中,我获得以 [mm] 为单位的深度并将其转换为米。

这是我的尝试,使用 np.mgrid 在 numpy 数组中计算 uv,这避免了缓慢的循环并允许利用 numpy 的通用函数。

import numpy as np
depth = np.random.uniform(size=(4,4)) # Just so this sample can be run
grid = np.mgrid[0:depth.shape[0],0:depth.shape[1]]
u, v = grid[0], grid[1]
z = depth / scaling_factor
adjusted_z = z / focal_length
x = (u - center_x) * adjusted_z
y = (v - center_y) * adjusted_z
color_points = np.stack([x,y,z], axis=-1).reshape(-1,3)

请注意,我没有为 z=0 筛选 color_points,但您可以使用 color_points[z.reshape(-1) != 0] 进行筛选。另请注意,我的 color_points 的排序方式与您的不同(uv 之前)。在深度估计场景中可能无关紧要。