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)]
x in range(crop)
, x
only goes up to crop - 1
, the last entry in the x dimension is always droppedx in range(crop+1)
, x
it goes up to crop
, that will result in a slice arr[crop:-0, ...]
which has the shape [0, y_dim, z_dim]
I know the usual answer, just drop the upper limit, like this: arr[crop:, :, :]
. Usually that's quite convenient. But how do I do that in the list comprehension ?
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)]
Use a ternary if..else
with None
:
>>> 'abc'[:None if 1 else -1]
'abc'
>>> 'abc'[:None if 0 else -1]
'ab'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With