刚性转换 - Python - 加速

时间:2016-11-24 15:38:39

标签: python performance numpy rigid-bodies

我有关于更快计算刚性转换的方法的问题(是的,我知道我可以简单地使用库,但需要自己编写代码)。

我需要计算x'和y'对于给定图像中的每个x,y。我的主要瓶颈是所有坐标的点积(此后的插值不是问题)。目前我实施了三个选项:

  1. 列表理解

    result = np.array([[np.dot(matrix, np.array([x, y, 1])) for x in xs] for y in ys])
    
  2. 简单双 - for循环

    result = np.zeros((Y, X, 3))
    for x in xs:
        for y in ys:
            result[y, x, :] = np.dot(matrix, np.array([x, y, 1]))
    
  3. np.ndenumerate

    result = np.zeros((Y, X, 3))
    for (y, x), value in np.ndenumerate(image):
        result[y, x, :] = np.dot(matrix, np.array([x, y, 1]))
    
  4. 512x512图像中最快的方式是列表理解(比np.ndenumerate快约1.5倍,比循环加倍快1.1倍。)

    有没有办法更快地做到这一点?

2 个答案:

答案 0 :(得分:3)

您可以使用np.indicesnp.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.T

答案 1 :(得分:3)

借鉴this post,创建1D数组而不是2D3D网格并在运行中broadcasted使用它们的想法内存效率的操作,从而实现性能优势,这是一种方法 -

out = ys[:,None,None]*matrix[:,1] + xs[:,None]*matrix[:,0] + matrix[:,2]

如果您为xs尺寸的图片覆盖了ys512x512的所有索引,我们会使用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