使用Python高效地查找每个像素中的点

使用Python高效地查找每个像素中的点,python,numpy,Python,Numpy,我有一个代表一组像素的2D网格。对于每个像素,我有左上角的坐标 我还有一个很长的随机分布的2D点列表。我正在寻找一种有效的方法来找到每个像素中存在的点的索引 目前我有以下几点: import numpy as np xgrid = np.linspace(0,10,11) ygrid = np.linspace(0,10,11) X_random_points = np.random.rand(int(1e7))*10 Y_random_points = np.random.rand(int(

我有一个代表一组像素的2D网格。对于每个像素,我有左上角的坐标

我还有一个很长的随机分布的2D点列表。我正在寻找一种有效的方法来找到每个像素中存在的点的索引

目前我有以下几点:

import numpy as np
xgrid = np.linspace(0,10,11)
ygrid = np.linspace(0,10,11)

X_random_points = np.random.rand(int(1e7))*10
Y_random_points = np.random.rand(int(1e7))*10

for iterationX in range(0,len(xgrid)-1):
    for iterationY in range(0,len(ygrid)-1):
        valuesInCube = (X_random_points<xgrid[iterationX]) & (X_random_points>xgrid[iterationX-1]) & (Y_random_points<ygrid[iterationY]) &(Y_random_points>ygrid[iterationY-1])  
将numpy导入为np
xgrid=np.linspace(0,10,11)
ygrid=np.linspace(0,10,11)
X_random_points=np.random.rand(int(1e7))*10
Y_random_points=np.random.rand(int(1e7))*10
对于范围(0,len(xgrid)-1)内的迭代X:
对于范围(0,len(ygrid)-1)内的迭代:
valuesInCube=(X_random_pointsxgrid[iterationX-1])&(Y_random_pointsxgrid[iterationY-1])
我想知道是否有人知道如何使这一过程更快?

你可以使用它来矢量化整个操作,避免完全循环,只要像素之间的间隔在每个方向上都是均匀的。对于简单的情况,
xgrid
ygrid
都是整数,您只需

X_random_points = ...
Y_random_points = ...
x_pixels = np.floor(X_random_points)
y_pixels = np.floor(Y_random_points)
如果像素不在整数网格上,则必须知道它们之间的间距。在这种情况下,我建议使用
np.arange
而不是
np.linspace
来生成像素位置:

delta_x, delta_y = 0.5, 0.5
xgrid = np.arange(0, 5.1, delta_x)
ygrid = np.arange(0, 5.1, delta_y)

X_random_points = np.random.rand(int(1e7)) * 5
Y_random_points = np.random.rand(int(1e7)) * 5

x_pixels = np.floor(X_random_points / delta_x)
y_pixels = np.floor(Y_random_points / delta_y)

对于整数情况,您确实在做同样的事情,因为
delta_x
delta_y
都是
1

我可以给您提供一种可能仍然有用的相关方法。相反,您可以找到每个点属于哪个像素。函数
numpy.digitalize
scipy.stats.binned\u statistic\u 2d
在这里很有用
scipy.stats.bined_statistic_2d
感觉有点笨拙,因为它不仅仅是存储点,还需要为每个x、y点提供一些值

您应该注意,箱子编号从
1
(而不是
0
)开始计数


对于特定像素,您甚至可以从
x\u p
y\u p

中找到属于该像素的所有点,立方体中的
值应该包含什么?现在它是一个每次都会被重置的面具。你想数一数吗?
x_p, y_p = np.digitize(X_random_points, xgrid), np.digitize(Y_random_points, xgrid)

# OR #

_, _, _, (x_p, y_p) = scipy.stats.binned_statistic_2d(X_random_points, Y_random_points, np.zeros(len(X_random_points)), bins=(xgrid, ygrid), expand_binnumbers=True)