numpy -混合使用all()和any()的动态切片

z4bn682m  于 2023-04-30  发布在  其他
关注(0)|答案(1)|浏览(120)

我正在尝试动态切片点云numpy数组。切片将过滤x/y坐标落在由minxminymaxxmaxy定义的边界列表内的点
我以为我有一个工作的算法,但我面对The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
例如(这只是演示数据):

import numpy as np

bounds_list = [
  (0, 0, 5, 5),
  (8, 8, 10, 10)
]

#col0 --> x , col1 -->  y , col2 --> z
random_arr = np.array([10, 10, 100]) * np.random.rand(100, 3)

def filter_by_bounds(arr):
  slices = np.array([np.array([bounds[0] <= arr[0] <= bounds[2], bounds[1] <= arr[1] <= bounds[3]]).all() for bounds in bounds_list]).any()
  return arr[slices]

filtered_arr = filter_by_bounds(random_arr)
print(filtered_arr)

在这个演示中,我想检索所有x/y坐标至少在一个边界内的点

rjjhvcjd

rjjhvcjd1#

你可以像这样过滤它:

def filter_by_bounds(arr):
    x = random_arr[:, 0]
    y = random_arr[:, 1]
    include = np.full(arr.shape[0], False)
    for bounds in bounds_list:
        include |= (bounds[0] <= x) & (x <= bounds[2]) & (bounds[1] <= y) & (y <= bounds[3])
    return arr[include]

这包括匹配某个界限的任何点。它使用矢量化来搜索匹配点。

相关问题