2017-02-17 49 views
2

有人可以给我解释一下这段代码的第二行呢?的Python - numpy的MGRID并重塑

objp = np.zeros((48,3), np.float32) 
objp[:,:2] = np.mgrid[0:8,0:6].T.reshape(-1,2) 

有人能向我解释究竟是什么np.mgrid [0:6:8,0]代码的代码的一部分,在做什么,到底是什么T.reshape(-1,2)的一部分是在做?

感谢和良好的工作!

+1

它创建了一个(2,8,6)阵列,它调换到(6,8,2),并重塑至(48.2) – hpaulj

+0

感谢@Bo鹏,我有同样的疑问 – tpk

回答

1

第二行创建一个multi-dimensional mesh gridtransposes它,reshapes它使它代表两列并将其插入到objp数组的前两列中。

击穿:

np.mgrid [0:8,0:6]创建以下MGRID:

>> np.mgrid[0:8,0:6] 
array([[[0, 0, 0, 0, 0, 0], 
     [1, 1, 1, 1, 1, 1], 
     [2, 2, 2, 2, 2, 2], 
     [3, 3, 3, 3, 3, 3], 
     [4, 4, 4, 4, 4, 4], 
     [5, 5, 5, 5, 5, 5], 
     [6, 6, 6, 6, 6, 6], 
     [7, 7, 7, 7, 7, 7]], 

     [[0, 1, 2, 3, 4, 5], 
     [0, 1, 2, 3, 4, 5], 
     [0, 1, 2, 3, 4, 5], 
     [0, 1, 2, 3, 4, 5], 
     [0, 1, 2, 3, 4, 5], 
     [0, 1, 2, 3, 4, 5], 
     [0, 1, 2, 3, 4, 5], 
     [0, 1, 2, 3, 4, 5]]]) 

的.T转置矩阵,并且.reshape(-1 ,2)然后将其重塑为两列两列数组形状。然后这两列是替换原始数组中两列的正确形状。

3

看到这些最简单的方法是使用较小的值mgrid

In [11]: np.mgrid[0:2,0:3] 
Out[11]: 
array([[[0, 0, 0], 
     [1, 1, 1]], 

     [[0, 1, 2], 
     [0, 1, 2]]]) 

In [12]: np.mgrid[0:2,0:3].T # (matrix) transpose 
Out[12]: 
array([[[0, 0], 
     [1, 0]], 

     [[0, 1], 
     [1, 1]], 

     [[0, 2], 
     [1, 2]]]) 

In [13]: np.mgrid[0:2,0:3].T.reshape(-1, 2) # reshape to an Nx2 matrix 
Out[13]: 
array([[0, 0], 
     [1, 0], 
     [0, 1], 
     [1, 1], 
     [0, 2], 
     [1, 2]]) 

然后objp[:,:2] = 0号和1号objp列设置为这个结果。