首页 > 解决方案 > 在python中将一组3D点转换为高度图像的最快方法

问题描述

我正在尝试将一组 3D 点转换为高度图(显示点与地板的最大位移的 2d 图像)

我能想到的唯一方法是编写一个遍历所有点并更新高度图的 for 外观,这种方法非常慢。

import numpy as np

heightmap_resolution = 0.02

# generate some random 3D points
points =  np.array([[x,y,z] for x in np.random.uniform(0,2,100) for y in np.random.uniform(0,2,100) for z in np.random.uniform(0,2,100)])


heightmap = np.zeros((int(np.max(points[:,1])/heightmap_resolution) + 1,
                  int(np.max(points[:,0])/heightmap_resolution) + 1))

for point in points:
    y = int(point[1]/heightmap_resolution)
    x = int(point[0]/heightmap_resolution)
    if point[2] > heightmap[y][x]:
        heightmap[y][x] = point[2]

我想知道是否有更好的方法来做到这一点。非常感谢任何改进!

标签: pythonperformance3dheightmap

解决方案


直觉:如果你发现自己在 numpy 中使用 for 循环,你可能需要再次检查 numpy 是否有针对它的操作。我看到你想比较项目以获得最大,我不确定结构是否重要,所以我改变了它。

第二点是高度图预先分配了很多你不会使用的内存。尝试使用带有元组 (x,y) 作为键的字典或这个(数据框)

import numpy as np
import pandas as pd

heightmap_resolution = 0.02

# generate some random 3D points
points =  np.array([[x,y,z] for x in np.random.uniform(0,2,100) for y in np.random.uniform(0,2,100) for z in np.random.uniform(0,2,100)])
points_df = pd.DataFrame(points, columns = ['x','y','z'])
#didn't know if you wanted to keep the x and y columns so I made new ones.
points_df['x_normalized'] = (points_df['x']/heightmap_resolution).astype(int)
points_df['y_normalized'] = (points_df['y']/heightmap_resolution).astype(int)
points_df.groupby(['x_normalized','y_normalized'])['z'].max()

推荐阅读