Numpy:获取 "Valid" 区域的边界角

Numpy: Get Boundary Corners of "Valid" Region

我有一个布尔值的 n 维 numpy 数组。我想找到能够切入数组的索引,我的切片包含所有 True 值和尽可能少的 False 值。

用较少的数学术语来说,基本上我有一个 3D 图像,我希望能够根据我定义的给定函数自动裁剪它(例如只关心标有绿色的部分)。最好的方法是什么?首选 n 维解决方案,以便我将来可以用于所有图像类型。

一种可能的方法是使用numpy.nonzero获取True值的所有索引,然后使用每个维度中的最小值和最大值来构造切片:

def bounding_slices(a):
    indices = np.nonzero(a)
    # indices is an tuple of arrays containing the indices of the non-zero elements
    # (False is interpreted as zero) with each array corresponding to one dimension
    slices = []
    for indices_in_dimension in indices:
      slices.append(slice(
          np.min(indices_in_dimension),  # start slice at lowest index in dimension
          np.max(indices_in_dimension) + 1  # end slice after (+ 1) highest index
      ))
    return slices