【问题标题】:Is there a quick method to project points onto an certain grid?有没有一种快速的方法将点投影到某个网格上?
【发布时间】:2020-05-11 08:24:12
【问题描述】:

我现在正在尝试将具有 3 维坐标 (x,y,z) 的 n 个点投影到具有一定大小(如 64*64)的 xy 网格上,当然这样的 n 个点的坐标在此受到限制网格。

目标是打印投影到每个网格元素上的点的 z 坐标。我写了两个for循环,但是有没有更好的方法来避免使用for循环来更快地运行它?

for i in range(XY_grid.shape[0]):
    x = np.where((X_coordinate > i) & (X_coordinate <= i + 1), 1, 0)
    for j in range(XY_grid.shape[1]):
        y = np.where(( Y_coordinate > j) & (Y_coordinate <= j + 1), 1, 0)  
        print(x * y * Z_coordinate)

【问题讨论】:

  • 打印声明print(x * y * Z_coordinate)的目的是什么?
  • 你的输入点和网格形状是什么?您正在将坐标与整数进行比较,这是否意味着您的坐标已标准化为网格步长?

标签: python numpy


【解决方案1】:

我认为您想要的是 2D 直方图:

import numpy as np

# generate some data (x, y, z)
x = np.arange(100)
y = np.random.rand(100)
z = np.arange(100)[::-1] * 1.5

# grid (x, y) onto a defined grid (0-127) in x and y
grid, xe, ye = np.histogram2d(x, y, bins=(np.arange(128), np.arange(128)), weights=None)

grid.sum()
>>> 100.0 # all data is in the grid (was only 100 points)

您可以使用weight 参数添加z 值:

# grid (x, y) onto a defined grid (0-127) in x and y
grid, xe, ye = np.histogram2d(x, y, bins=(np.arange(128), np.arange(128)), weights=z)

grid.sum()
>>> 7425.0

z.sum()
>>> 7425.0 # all z values are in the produced grid

您可以更改bins 的宽度等以使它们不均匀,或保持它们均匀分布以形成规则网格。

生成的 grid 是一个 2D numpy 数组,其中包含落入每个 bin 的所有 z 信息。您可以轻松地 print 它或循环遍历它以依次获取每个元素。

【讨论】:

    【解决方案2】:

    要打印与X_coordinateY_coordinate 中特定点对应的Z_coordinate 的所有条目,您可以这样做:

    for i in range(XY_grid.shape[0]):
        for j in range(XY_grid.shape[1]):
            print(Z_coordinate[np.logical_and(X_coordinate==i, Y_coordinate==j)])
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-06-30
      • 1970-01-01
      • 1970-01-01
      • 2022-09-29
      • 2021-05-02
      • 1970-01-01
      • 2018-01-07
      • 1970-01-01
      相关资源
      最近更新 更多