【问题标题】:Applying a Fast Coordinate Transformation in Python在 Python 中应用快速坐标变换
【发布时间】:2016-01-27 10:11:05
【问题描述】:

我有一个简单的 2x2 变换矩阵,s,它对坐标的一些线性变换进行编码,使得 X' = sX

我使用 np.meshgrid() 函数在网格上生成了一组均匀分布的坐标,此时我遍历每个坐标并在坐标级别的坐标上应用变换。不幸的是,这对于大型阵列来说非常慢。有没有快速的方法来做到这一点?谢谢!

import numpy as np

image_dimension = 1024
image_index = np.arange(0,image_dimension,1) 
xx, yy = np.meshgrid(image_index,image_index)

# Pre-calculated Transformation Matrix.
s = np.array([[ -2.45963439e+04,  -2.54997726e-01], [  3.55680731e-02, -2.48005486e+04]])

xx_f = xx.flatten()
yy_f = yy.flatten()

for x_t in range(0, image_dimension*image_dimension):

    # Get the current (x,y) coordinate.
    x_y_in = np.matrix([[xx_f[x_t]],[yy_f[x_t]]])

    # Perform the transformation with x.
    optout =  s * x_y_in

    # Store the new coordinate.
    xx_f[x_t] = np.array(optout)[0][0]
    yy_f[x_t] = np.array(optout)[1][0]

# Reshape Output
xx_t = xx_f.reshape((image_dimension, image_dimension))
yy_t = yy_f.reshape((image_dimension, image_dimension))

【问题讨论】:

    标签: python numpy grid transform coordinate


    【解决方案1】:

    您可以使用 numpy dot 函数来获取您的 matices 的点积:

    xx_tn,yy_tn = np.dot(s,[xx.flatten(),yy.flatten()])
    
    xx_t = xx_tn.reshape((image_dimension, image_dimension))
    yy_t = yy_tn.reshape((image_dimension, image_dimension))
    

    哪个更快

    【讨论】:

      【解决方案2】:

      Python 中的循环很慢。最好使用vectorization。 简而言之,这个想法是让 numpy 在 C 中做循环,这要快得多。

      您可以将您的问题表达为矩阵乘法 X' = sX,您可以将所有点放在 X 中,只需调用一次 numpy 的点积即可将它们全部转换:

      xy = np.vstack([xx.ravel(), yy.ravel()])
      xy_t = np.dot(s, xy)
      xx_t, yy_t = xy_t.reshape((2, image_dimension, image_dimension))
      

      【讨论】:

      • @kazemakase 我正在计时你的答案,我发现它比我的要快得多,显然vstackarray(list) 的任何组合快得多并直接传递列表。你知道这是为什么吗?
      • @NoelSegura 我猜这是因为我使用了ravel 而不是你的flatten。如果我正确阅读了文档,flatten 总是会创建数组的副本,而ravel 会尝试创建视图。
      • @kazemakase, ravelflatten 稍快,但vstack 似乎是最大的因素。两种方法我都试过了,np.dot(s,np.vstack([xx.ravel(),yy.ravel()]))np.dot(s,np.vstack([xx.flatten(),yy.flatten()])) 稍微快一点。但是np.dot(s,np.vstack([xx.ravel(),yy.ravel()]))np.dot(s,[xx.ravel(),yy.ravel()]) 快很多
      • @NoelSegura 有趣,在我的机器上,vstack 版本稍慢。
      • @kazemakase,真的,这很奇怪。你能试试这个代码吗? pastebin.com/6BPu8mAa
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-07-05
      • 2023-02-02
      • 1970-01-01
      • 2020-03-29
      • 2014-11-02
      • 2010-11-20
      相关资源
      最近更新 更多