如何获取"numpy.array"的边界? [英] How to get Boundaries of an 'numpy.array'?
本文介绍了如何获取"numpy.array"的边界?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我有d
维np.array
,如何获取边界的标记?
If I have an d
dimensional np.array
, how can I get the indicies of the boundary?
例如,在2d中,
test = np.arange(16).reshape((4, 4))
test
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11],
[12, 13, 14, 15]])
现在我想了解边界
array([[ True, True, True, True],
[ True, False, False, True],
[ True, False, False, True],
[ True, True, True, True]])
如果有效并且在任意数量的维度上都有效,则非常好,但必须至少工作3个.数组不一定是超立方体,而可能是超矩形:在所有维度上的网格点数不一定相同,与示例不同.
Great if efficient and works for arbitrary number of dimensions, but it has to work at least 3. The array is not a necessarily a hypercube, but potentially a hyperrectangle: the number of grid points in all dimension are not necessarily the same, unlike in the example.
对于形状为(4, 5, 6)
的数组,预期输出为
For an array of shape (4, 5, 6)
, the expected output is
array([[[ True, True, True, True, True, True],
[ True, True, True, True, True, True],
[ True, True, True, True, True, True],
[ True, True, True, True, True, True],
[ True, True, True, True, True, True]],
[[ True, True, True, True, True, True],
[ True, False, False, False, False, True],
[ True, False, False, False, False, True],
[ True, False, False, False, False, True],
[ True, True, True, True, True, True]],
[[ True, True, True, True, True, True],
[ True, False, False, False, False, True],
[ True, False, False, False, False, True],
[ True, False, False, False, False, True],
[ True, True, True, True, True, True]],
[[ True, True, True, True, True, True],
[ True, True, True, True, True, True],
[ True, True, True, True, True, True],
[ True, True, True, True, True, True],
[ True, True, True, True, True, True]]], dtype=bool)
推荐答案
您可以通过构建切片的元组来实现此目的,例如
You could do this by constructing a tuple of slices, e.g.
import numpy as np
def edge_mask(x):
mask = np.ones(x.shape, dtype=bool)
mask[x.ndim * (slice(1, -1),)] = False
return mask
x = np.random.rand(4, 5)
edge_mask(x)
# array([[ True, True, True, True, True],
# [ True, False, False, False, True],
# [ True, False, False, False, True],
# [ True, True, True, True, True]], dtype=bool)
这篇关于如何获取"numpy.array"的边界?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文