代码之家  ›  专栏  ›  技术社区  ›  Layman

NumPy中最大采样优化点云到体素网格

  •  1
  • Layman  · 技术社区  · 11 月前

    我有两个数组,分别表示点坐标和值。为了从该点云中获取最大样本,我正在初始化一个具有所需大小的网格,并在每个点上循环以分配最大值:

    N = 1000000
    coords = np.random.randint(0, 256, size=(N, 3))
    vals = np.random.rand(N, 3)
    
    grid = np.zeros((3, 256, 256, 256), dtype=np.float16)
    for i, pt in enumerate(coords):
        x, y, z = pt
    
        grid[0, x, y, z] = max(grid[0, x, y, z], vals[i, 0])
        grid[1, x, y, z] = max(grid[1, x, y, z], vals[i, 1])
        grid[2, x, y, z] = max(grid[2, x, y, z], vals[i, 2])
    
    

    有没有一种方法可以在没有for循环(非常慢)的情况下通过NumPy做到这一点?

    1 回复  |  直到 11 月前
        1
  •  1
  •   m-sarabi    11 月前

    np.maximum.at 可用于执行 max 在特定指标下进行操作。

    例如,如果我们有两个数组 arr1 arr2 比较和 indices array,我们可以这样做:

    arr1 = np.array([1, 2, 3, 4, 5])
    arr2 = np.array([10, 1, 8, 7, 3])
    indices = np.array([0, 1, 2, 1, 4])
    
    # Perform in-place maximum update
    np.maximum.at(arr1, indices, arr2)
    
    print(arr1)
    # Output: [10  7  8  4  5]
    

    所以我相信在你的情况下,你可以这样做:

    indices = coords[:, 0], coords[:, 1], coords[:, 2]
    
    np.maximum.at(grid[0], indices, vals[:, 0])
    np.maximum.at(grid[1], indices, vals[:, 1])
    np.maximum.at(grid[2], indices, vals[:, 2])