lhk - 3 months ago 25

Python Question

I've got a 3D array and would like to split it into many subvolumes.

This is my code so far:

`# this results in a 3D array`

arr = trainMasks[0, 0, :, :, :]

crop = 3

arrs = [arr[x:-(crop - x), y:-(crop - y), z:-(crop - z)]

for x in range(crop + 1)

for y in range(crop + 1)

for z in range(crop + 1)]

- If I use ,
`x in range(crop)`

only goes up to`x`

, the last entry in the x dimension is always dropped`crop - 1`

- If I use ,
`x in range(crop+1)`

it goes up to`x`

, that will result in a slice`crop`

which has the shape`arr[crop:-0, ...]`

`[0, y_dim, z_dim]`

I know the usual answer, just drop the upper limit, like this:

`arr[crop:, :, :]`

Answer

In cases like this it is better to avoid negative indexes.

Remeber that for `i>0`

, `a[-i]`

is equivalent to `a[len(a)-i]`

. But in your case, you also need to work for `i==0`

.

This works:

```
d1, d2, d3 = arr.shape
arrs = [arr[ x : d1-(crop-x), y : d2-(crop-y), z : d3-(crop-z)]
for x in range(crop + 1)
for y in range(crop + 1)
for z in range(crop + 1)]
```