python - 从二维数组中选择布尔值时的 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
解决方案
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.])
推荐阅读
- javascript - 如何在 JavaScript 中使用 Python 字符串索引?
- shell - 如何选择垂直列到水平列?
- ruby-on-rails - 将 twitter bootstrap gem 从 2.x 升级到 3.x 或 4.x 会破坏 UI 样式
- javascript - 数据不显示。错误:无法获取/表达 API
- angular - 试图将事件从父级传递给子级不起作用。角 8
- node.js - /bin/sh: =: 从自定义映像运行 docker 容器时未找到
- java - 在 tomat 上部署的根映射(“/”)上的 Spring Boot 404。(轻松依赖问题)
- python - 如何修剪 keras ResNet50 预训练权重(.h5 文件)?我只有 .h5 权重文件。(我已经成功加载了 keras 权重)
- c# - 如何在 C# 中评估包含局部变量名称的字符串作为代码
- sql-server - SQL:消息“无效的对象名称”是什么意思?