I have a 3D volume and I modify slices along different axis.
JavaScript
x
5
1
for idx in range(len(self.volume)):
2
for axe in range(self.volume.ndim): # = range(3)
3
slice_ = np.take(self.volume, idx, axis = axe)
4
''' Do something '''
5
(np.take is equivalent of writing self.volume[idx], self.volume[:, idx] and self.volume[:, :, idx])
Finally, I want to assign a new slice in my volume along the axis :
JavaScript
1
7
1
if axe == 0:
2
self.volume[idx] = new_slice
3
elif axe == 1:
4
self.volume[:,idx] = new_slice
5
else:
6
self.volume[:,:,idx] = new_slice
7
This is where I need some help. I can’t figure out a cleaner way of doing this assignment. (I would like something as clean as np.take())
I have tried np.insert, np.insert_along_axis, np.put, np.put_along_axis… but I am clearly missing something out.
Any ideas ? :)
Have a great day
Advertisement
Answer
There may be a more elegant solution but the following should work:
JavaScript
1
4
1
s = [slice(None)]*self.volume.ndim
2
s[axe] = slice(idx,idx+1)
3
self.volume[tuple(s)] = np.expand_dims(new_slice, axe)
4
Alternatively, you can try:
JavaScript
1
4
1
self.volume = np.swapaxes(self.volume, 0, axe)
2
self.volume[idx] = new_slice
3
self.volume = np.swapaxes(self.volume, 0, axe)
4