0

I have some 3D numpy arrays that need to be transformed in various ways. E.g.:

x.shape = (4, 17, 17)

This array is 1 sample of 4 planes, each of size 17x17. What is the most efficient way to transform each plane: flipud, fliplr, and rot90? Is there a better way than using a for loop? Thanks!

for p in range(4):
    x[p, :, :] = np.fliplr(x[p, :, :])
1
  • could you use an example array and indicate what you want it to look like... eg. a = np.arange(3*4*5).reshape(3,4,5) ... Commented Dec 24, 2016 at 0:55

1 Answer 1

1

Look at the code of these functions:

def fliplr(...):
   ....
   return m[:, ::-1]

In other words it returns a view with reverse slicing on the 2nd dimension

Your x[p, :, :] = np.fliplr(x[p, :, :] applies that reverse slicing to the last dimension, so the equivalent for the whole array should be

x[:, :, ::-1]

flipping the 2nd axis would be

x[:, ::-1, :]

etc.

np.rot90 has 4 case (k); for k=1 it is

return fliplr(m).swapaxes(0, 1)

in other words m[:, ::-1].swapaxes(0,1)

To work on your planes you would do something like

m[:, :,::-1].swapaxes(1,2)

or you could do the swapaxes/transpose first

m.transpose(0,2,1)[:, :, ::-1]

Does that give you enough tools to transform the plane's in what ever way you want?

As I discussed in another recent question, https://stackoverflow.com/a/41291462/901925, the flip... returns a view, but the rot90, with both flip and swap, will, most likely return a copy. Either way, numpy will be giving you the most efficient version.

Sign up to request clarification or add additional context in comments.

Comments

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.