将齐次坐标恢复为二维的有用方法?

问题描述 投票:0回答:3

是否有一些 numpy 糖可以将齐次坐标恢复为二维坐标。

所以这个:

[[4,8,2],
6,3,2]]

变成这样:

[[2,4],
[3,1.5]]
numpy coordinates projection
3个回答
4
投票

如果你的输入是一个名为

x
的向量,你可以这样做

x[:-1]/x[-1]

完整示例:

import numpy as np
x = np.array([6,3,2])
x[:-1]/x[-1]    # array([ 3. ,  1.5])

您还可以将其应用于数组中的多个坐标:

xs = np.array([[4,8,2],[6,3,2]])
np.array([x[:-1]/x[-1] for x in xs])    # array([[ 2. ,  4. ],
                                        #        [ 3. ,  1.5]])

如果你想重用它,你可以定义一个函数

homogen
:

homogen = lambda x: x[:-1]/x[-1]

# previous stuff becomes something like
np.array([homogen(x) for x in xs])

2
投票

一种利用

broadcasted
元素除法的方法 -

from __future__ import division

a[:,:2]/a[:,[-1]]

我们可以使用

a[:,-1,None]
a[:,-1][:,None]
a[:,-1].reshape(-1,1)
来代替
a[:,[-1]]
。通过
a[:,[-1]]
,我们保持调光数量不变,让我们执行广播划分。

另一个

np.true_divide
再次使用
broadcasting
-

np.true_divide(a[:,:2], a[:,[-1]])

样品运行 -

In [194]: a
Out[194]: 
array([[4, 8, 2],
       [6, 3, 2]])

In [195]: a[:,:2]/a[:,[-1]]
Out[195]: 
array([[ 2. ,  4. ],
       [ 3. ,  1.5]])

In [196]: np.true_divide(a[:,:2], a[:,[-1]])
Out[196]: 
array([[ 2. ,  4. ],
       [ 3. ,  1.5]])

0
投票

Numpy 在内部处理广播,因此您可以使用以下方法来避免 for 循环:

x/x[:,-1].reshape(-1,1)

示例运行:

>>> import numpy as np
>>> x = np.hstack((np.random.randint(0,10,(3,2)), np.ones((3,1))*10))
>>> x
array([[ 1.,  8., 10.],
   [ 7.,  9., 10.],
   [ 1.,  9., 10.]])

>>> x/x[:,-1].reshape(-1,1)
array([[0.1, 0.8, 1. ],
   [0.7, 0.9, 1. ],
   [0.1, 0.9, 1. ]])
© www.soinside.com 2019 - 2024. All rights reserved.