给定一个形状为(N,2)的数组,我想为每个点制作一个大小为d x d的补丁。
例如,如果

d = 3
points = [[3, 2], [1, 2]]
patchs = array([[[[2, 1],[3, 1],[4, 1]],
                 [[2, 2],[3, 2],[4, 2]],
                 [[2, 3],[3, 3],[4, 3]]], [[[0, 1],[1, 1],[2, 1]],
                                           [[0, 2],[1, 2],[2, 2]],
                                           [[0, 3],[1, 3],[2, 3]]]])


我只用了一点就做到了,但是我找不到一种聪明的方法来避免N上的循环。这是我所做的:

p = [3,2]
xs = p[0] + [-1,0,1]
ys = p[1] + [-1,0,1]
res = np.transpose([np.tile(xs, len(ys)), np.repeat(ys, len(xs))])

最佳答案

这是一种利用broadcasting进行分配的矢量化方法-

hd = d//2 # half patch size
r = np.arange(-hd,hd+1)

out = np.empty((len(points),d,d,2), dtype=points.dtype)
out[...,0] = points[:,0,None,None] + r
out[...,1] = points[:,1,None,None] + r[:,None]


一百万点的运行时测试-

In [372]: points = np.random.randint(0,9,(1000000,2))

In [373]: %%timeit
     ...: hd = d//2 # half patch size
     ...: r = np.arange(-hd,hd+1)
     ...:
     ...: out = np.empty((len(points),d,d,2), dtype=points.dtype)
     ...: out[...,0] = points[:,0,None,None] + r
     ...: out[...,1] = points[:,1,None,None] + r[:,None]
10 loops, best of 3: 69.9 ms per loop

关于python - 点采样,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47712482/

10-09 18:56