简体   繁体   中英

Get NumPy slice from start/end coordinates

Let's say I have a 3D 100x100x100 array and have some starting and ending coordinates, eg:

(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))]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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