如何扩大一个numpy数组

How to dilate a numpy array

我有一个形状为 (1000,3) 的 numpy 点数组 其中轴 1 取值 [x,y,1]

这些点是网格上的离散值,因此示例数组如下所示:

array=([1,2,1],[4,5,1],[2,3,1],...,[xN,yN,1])

我想扩大这个二维数组,我的意思是,对于数组中的每个 [x,y,1] 坐标,如果 [x±1,y±1,1] 不在数组中,则将其附加到数组中。

目前我正在使用以下代码执行此操作:

np.append(array, [array[:,0],array[:,1]+1,1])
np.append(array, [array[:,0]+1,array[:,1],1])
np.append(array, [array[:,0]+1,array[:,1]+1,1])
np.append(array, [array[:,0]-1,array[:,1],1])
np.append(array, [array[:,0],array[:,1]-1,1])
np.append(array, [array[:,0]-1,array[:,1]-1,1])
np.append(array, [array[:,0]+1,array[:,1]-1,1])
np.append(array, [array[:,0]-1,array[:,1]+1,1])

然后我正在使用 np.unique(array) 来减少独特的元素。这个方法可以,但是在超过100000点的大数组上运行太慢了,感觉不是很顺利的解法。必须有一种方法可以做到这一点,而无需复制那么多点,然后必须找到所有独特的实例。有没有不同的(阅读:更快)方式来做我正在做的事情?

2000 x 4000 x 200 只需查找 table 即可。与 np.unique 方法相比,在略低于一百万个坐标的情况下,我的速度提高了约 5 倍。

lookup table:  2.18715, np.unique: 11.40247

代码:

import numpy as np
from numpy.lib.stride_tricks import as_strided
from time import time

coords = np.unique(np.random.randint(0, 2000*4000*200, (1000000,)))
coords = np.c_[coords // (4000*200), (coords // 200) % 4000, coords % 200]

t = [time()]

ws = np.empty((2002, 4002, 202), dtype=np.uint8)
ws = as_strided(ws, (2000, 4000, 200, 3, 3, 3), 2 * ws.strides)

ws[tuple(coords.T)] = np.arange(27).reshape(3, 3, 3)
unq = ws[tuple(coords.T)] == np.arange(27).reshape(3, 3, 3)
result = (coords[:, None, None, None, :] + np.moveaxis(np.indices((3, 3, 3)) - 1, 0, -1))[unq]
del ws

t.append(time())

result2 = np.unique((coords[:, None, None, None, :] + np.moveaxis(np.indices((3, 3, 3)) - 1, 0, -1)).reshape(-1, 3), axis = 0)

t.append(time())

print('lookup table: {:8.5f}, np.unique: {:8.5f}'.format(*np.diff(t)))