首页 > 解决方案 > 从二维数组中选择布尔值时的 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 我的第二个代码有什么问题?

github 上提供了lidar.txt 数据文件: https ://github.com/OSGeoLabBp/tutorials/blob/master/english/data_processing/lessons/code/lidar.txt

标签: pythonnumpy

解决方案


It looks like your issue is with the shape of array vp.

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

Remove the “1” from your np.zeros call and it should work:

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

推荐阅读