采样补丁点

时间:2017-12-08 10:32:39

标签: python numpy vectorization

给定一个形状let result = temp1.reduce(function(res, obj) { console.log(res, obj); Object.keys(obj).forEach(function(k) { res[k] = res[k] || []; res[k] = res[k].concat(obj[k]); }); return res; }, []); 的数组我想为每个点选取一个大小为lodash的补丁。 例如,如果

(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]]]])

1 个答案:

答案 0 :(得分:1)

这是一种利用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]

100万分的运行时测试 -

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