2

I was wondering if there is a way to reverse a 3d numpy array? Like in 1d case we can go from [1 2 3] to [3 2 1]. Is there something similar for 3d?

Thanks

3
  • 3
    First you need to define what it means to "reverse" a 3D array. Commented Feb 12, 2015 at 17:00
  • 2
    what do you expect a reversed 3d array to look like ? Commented Feb 12, 2015 at 17:01
  • my_array[::-1] will reverse any array ... but i doubt thats what you mean Commented Feb 12, 2015 at 17:01

2 Answers 2

5

Do you mean reverse it along an particular axis?

For example, if we have a color image of the size height x width x 3 where the last axis is red, green, blue (RGB) pixels, and we want to convert it to blue, green, red (BGR):

image_bgr = image[:, :, ::-1]

If you'd prefer, you can even write that as:

image_bgr = image[..., ::-1]

As a more complete example, consider this:

import numpy as np

# Some data...
x = np.arange(3 * 4 * 5).reshape(5, 4, 3)

print x[0,0,:]

# Reverse the last axis
y = x[:, :, ::-1]

print y[0,0,:]

In general, though, you can use this to reverse any particular axis. For example, you could just as easily have done:

y = x[:, ::-1, :]

To reverse the second axis.

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

1 Comment

Thanks a lot. Your answer helped get the correct results! :)
0

To do this, you can use the flip function from the numpy library, whose parm axis indicates the index along which the matrix needs to be reversed.

np.flip(x, axis=2)

this is the equivalent of

x[:, :, ::-1]

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.