关于如何更快地计算刚性转换,我有以下问题(是的,我知道我可以简单地使用库,但需要自己编写代码)。
对于给定图像中的每一个x,y,我需要计算x‘和y’。我的主要瓶颈是所有坐标的点积(这之后的插值不是问题)。目前,我实施了三个备选方案:
for循环
结果= np.zeros((Y,X,3))对x中的x:y在ys:结式,x,:=np.dot(矩阵,np.array(x,y,1))512x512图像中最快的方法是列表理解(比np.ndenumerate快1.5倍,比double for循环快1.1倍)。
有办法更快地做到这一点吗?
发布于 2016-11-24 17:31:01
借鉴this post的思想,创建1D数组而不是2D或3D网格,并将它们与实时broadcasted操作一起使用以提高内存效率,从而获得性能上的好处。
out = ys[:,None,None]*matrix[:,1] + xs[:,None]*matrix[:,0] + matrix[:,2]如果你用xs和ys覆盖512x512大小的图像的所有索引,我们会用np.arange创建它们,就像这样-
ys = np.arange(512)
xs = np.arange(512)运行时测试
函数定义-
def original_listcomp_app(matrix, X, Y): # Original soln with list-compr.
ys = np.arange(Y)
xs = np.arange(X)
out = np.array([[np.dot(matrix, np.array([x, y, 1])) for x in xs] \
for y in ys])
return out
def indices_app(matrix, X, Y): # @Eric's soln
coords_ext = np.empty((Y, X, 3))
coords_ext[...,[1,0]] = np.rollaxis(np.indices((Y, X)), 0, start=3)
coords_ext[...,2] = 1
result = np.matmul(coords_ext,matrix.T)
return result
def broadcasting_app(matrix, X, Y): # Broadcasting based
ys = np.arange(Y)
xs = np.arange(X)
out = ys[:,None,None]*matrix[:,1] + xs[:,None]*matrix[:,0] + matrix[:,2]
return out时间安排和核查-
In [242]: # Inputs
...: matrix = np.random.rand(3,3)
...: X,Y = 512, 512
...:
In [243]: out0 = original_listcomp_app(matrix, X, Y)
...: out1 = indices_app(matrix, X, Y)
...: out2 = broadcasting_app(matrix, X, Y)
...:
In [244]: np.allclose(out0, out1)
Out[244]: True
In [245]: np.allclose(out0, out2)
Out[245]: True
In [253]: %timeit original_listcomp_app(matrix, X, Y)
1 loops, best of 3: 1.32 s per loop
In [254]: %timeit indices_app(matrix, X, Y)
100 loops, best of 3: 16.1 ms per loop
In [255]: %timeit broadcasting_app(matrix, X, Y)
100 loops, best of 3: 9.64 ms per loop发布于 2016-11-24 16:52:09
您可以使用np.indices和np.rollaxis生成一个3D数组,其中coords[i, j] == [i, j]。在这里坐标需要转换
然后,您所做的就是附加您所要求的1,并使用@
coords_ext = np.empty((Y, X, 3))
coords_ext[...,[1,0]] = np.rollaxis(np.indices((Y, X)), 0, start=3)
coords_ext[...,2] = 1
# convert to column vectors and back for matmul broadcasting
result = (matrix @ coords_ext[...,None])[...,0]
# or alternatively, work with row vectors and do it in the other order
result = coords_ext @ matrix.Thttps://stackoverflow.com/questions/40790219
复制相似问题