0

I have a 3D volume and I modify slices along different axis.

for idx in range(len(self.volume)): 
    for axe in range(self.volume.ndim): # = range(3)
        slice_ = np.take(self.volume, idx, axis = axe)
        ''' Do something '''

(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 :

    if axe == 0:
        self.volume[idx] = new_slice
    elif axe == 1:
        self.volume[:,idx] = new_slice
    else:
        self.volume[:,:,idx] = new_slice

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

1 Answer 1

1

There may be a more elegant solution but the following should work:

s = [slice(None)]*self.volume.ndim
s[axe] = slice(idx,idx+1)
self.volume[tuple(s)] = np.expand_dims(new_slice, axe)

Alternatively, you can try:

self.volume  = np.swapaxes(self.volume, 0, axe)
self.volume[idx] = new_slice
self.volume  = np.swapaxes(self.volume, 0, axe)
Sign up to request clarification or add additional context in comments.

3 Comments

The first method you propose doesn't work, I have this error : ValueError: could not broadcast input array from shape (512,512) into shape (512,1,512). The second method doesn't work either because I have 3 axis, and swapping only 2 axis messes with the volume.
I edited the first method, should be fine now. As for the second, it should work as long as you swap axes back after the assignment.
It works with the first method now. thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.