【发布时间】:2022-08-18 22:17:43
【问题描述】:
我有 100 万个随机点(float x, float y),它们在一个矩形区域内。现在我想把矩形分成很多个小矩形,可以得到每个小矩形的中心点坐标,比如[(0.5,0.5),(0.5,1.5)]。问题是如何快速知道每个随机点属于哪个小矩形!! 这是我的代码:
## generate the center point of each small rectangle.
def gen_center_coor(row = None, col = None,bias = None):
spatial = np.zeros((row*col,2))
a,b=np.meshgrid(np.arange(row),np.arange(col),indexing = \'ij\')
spatial[:,0], spatial[:,1] = a.reshape(-1),b.reshape(-1)
spatial += bias
return spatial
centerdot = gen_center_coor(row =320, col = 320,bias = 0.5)
## generate the number of points per small rectangle (randomnums)
## and random points (randdot)
randomnums = np.random.randint(low=5,high=15,size=320 * 320)
randrow = np.random.uniform(low=-0.5, high=0.5, size=sum(randomnums))
randcol = np.random.uniform(low=-0.5, high=0.5, size=sum(randomnums))
randdot_row = np.repeat(centerdot[:, 0], randomnums) + randrow
randdot_col = np.repeat(centerdot[:, 1], randomnums) + randcol
randdot = np.hstack((randdot_row.reshape(-1,1), randdot_col.reshape(-1, 1)))
## in fact, randomnums: just to verify your code
## you only have the randdot
## here is my main function, but it is too slow for me
for i in range(100):
gdnet = np.repeat(centerdot[i],randdot.shape[0]).reshape(randdot.shape[0],2)
np.where(np.abs(randdot - gdnet).max(-1)<0.5)[0]
-
您的矩形是否与 X/Y 轴对齐?另外,小矩形的大小都一样吗?