从二维数组中选择布尔值时Numpy索引错误



我有两个代码几乎相同的Python脚本。其中一个正在工作,另一个失败,并显示错误消息

Traceback (most recent call last):
File "np.py", line 24, in <module>
sec = pc[np.dot(pc1, vp) < tol]   # select points close to section
IndexError: boolean index did not match indexed array along dimension 1; dimension is 3 but corresponding boolean dimension is 1

正常运行的代码:

import numpy as np
a = np.loadtxt('lidar.txt', delimiter=',')
tol = 3
vp = np.array([7.32793492e-01, -6.80451099e-01, 3.08811740e+06])
a1 = np.hstack((a[:,0:2], np.full((a.shape[0], 1), 1)))
#sel = np.absolute(np.dot(a1, vp)) < tol
#sec = a[sel]
sec = a[np.absolute(np.dot(a1, vp)) < tol]
print(sec)

另一个失败:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" filter point on a vertical section
command line parameters: input_file, x1, y1, x2, y2, tolerance
vertical plain is defined by (x1,y1) and (x2,y2)
"""
import sys
import numpy as np
from math import hypot
x1 = 548750.0
y1 = 5129300.0
x2 = 548425.0
y2 = 5128950.0
tol = 3.0
# set up equation for vertical plain vp[0] * x + vp[1] * y + vp[2] = 0
vp = np.zeros((3, 1))
vp[0] = y1 - y2
vp[1] = x2 - x1
vp[2] = x1 * y2 - x2 * y1
vp = vp / hypot(vp[0], vp[1])               # normalize
pc = np.loadtxt('lidar.txt', delimiter=',') # load point cloud from text file
pc1 = np.hstack((pc[:,0:2], np.full((pc.shape[0], 1), 1)))  # homegenous coords
sec = pc[np.dot(pc1, vp) < tol]   # select points close to section
for i in range(sec.shape[0]):               # print out result
print("{:.3f} {:.3f} {:.3f}".format(pc[i][0], pc[i][1], pc[i][2]))

我找不出这两个解决方案的区别。我在Ubuntu 20.04上使用Python 3.8.5和NumPy 1.17.4我的第二个代码有什么问题?

lidar.txt数据文件在github上可用:https://github.com/OSGeoLabBp/tutorials/blob/master/english/data_processing/lessons/code/lidar.txt

看起来你的问题是与数组vp的形状有关。

>>> vp = np.array([7.32793492e-01, -6.80451099e-01, 3.08811740e+06])
>>> vp.shape
(3,)
>>> np.zeros((3, 1)).shape
(3, 1)

从np中删除"1"。调用0,它应该可以工作:

>>> np.zeros((3,)).shape
(3,)
>>> np.zeros((3,))
array([ 0.,  0.,  0.])

最新更新