在Python中将一组3D点转换为高度图像的最快方法

时间:2019-06-21 17:35:09

标签: python performance 3d heightmap

我正在尝试将一组3D点转换为高度图(一个2d图像,该图像显示了这些点相对于地面的最大位移)

我想出的唯一方法是编写遍历所有点并更新高度图的外观,这种方法相当慢。

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]

我想知道是否有更好的方法可以做到这一点。任何改进都将不胜感激!

1 个答案:

答案 0 :(得分:1)

直觉: 如果发现自己在numpy中使用了for循环,则可能需要再次检查numpy是否对其进行了操作。我看到您想比较商品以获取最大商品,但不确定结构是否重要,因此我进行了更改。

第二点是heightmap正在预分配大量您将不使用的内存。尝试使用以元组(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()