简体   繁体   English

从开始/结束坐标获取NumPy切片

[英]Get NumPy slice from start/end coordinates

Let's say I have a 3D 100x100x100 array and have some starting and ending coordinates, eg: 假设我有一个3D 100x100x100数组,并且有一些开始和结束坐标,例如:

(0,0,0) (50,20,20)

How can I get extract a subarray bounded by cuboid defined by those vertices? 我怎样才能 提取由这些顶点定义由长方体包围的子阵?

We can use slicing notation. 我们可以使用切片符号。 For this specific case that would be: 对于这种特定情况,将是:

subarray = the_array[0:50, 0:20, 0:20]

Of course the above will only work given we know the numbers (and dimension) in advance. 当然,只有在我们事先知道数字(和尺寸)的情况下,以上方法才有效。 A more sophisticated program is necessary if we are given two three-tuples: 如果给我们两个三元组,则需要一个更复杂的程序:

first = (0,0,0)
second = (50,20,20)

a0, b0, c0 = first
a1, b1, c1 = second
subarray = the_array[a0:a1, b0:b1, c0:c1]

But this is still not very elegant, since we hardcode the number of dimensions. 但这仍然不是很优雅,因为我们对维数进行了硬编码。 We can process two tuples (or iterables in general) of arbitrary size for that: 为此,我们可以处理两个任意大小的元组(或通常的可迭代对象):

first = (0,0,0)
second = (50,20,20)

subarray = the_array[tuple(slice(x,y) for x, y in zip(first, second))]

The upperbounds in slicing are always exclusive. 切片的上限始终是唯一的。 In case you want to add these, you can increment the upperbound: 如果要添加这些,可以增加上限:

subarray = the_array[0:51, 0:21, 0:21]

or: 要么:

subarray = the_array[a0:a1+1, b0:b1+1, c0:c1+1]

or: 要么:

subarray = the_array[tuple(slice(x,y+1) for x, y in zip(first, second))]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM