python - 在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]
我想知道是否有更好的方法来做到这一点。非常感谢任何改进!
解决方案
直觉:如果你发现自己在 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()
推荐阅读
- woocommerce - 更改特定页面上的缩略图大小
- r - 在 R Crosstalk 中绘制与 DataTable 的交互
- javascript - UIkit滑块居中模式怎么做?
- java - JAX-RS 和 RegEx @Paths 带空格
- python - 存储包含列表字段的数据框的最快方法
- django - 想知道它是否是第一个使用 django social 登录的用户?
- android - Android Paging 3.0 加载方法不起作用
- r - R - 块列表使用的 RAM 是否比读取/写入每个块少?
- apache - 从 http 更改为 https 后 URL 重定向不起作用
- python - 如何在 Pandas 数据框中查找每个列顺序的总和和计数?