Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you sequentially flip each dimension in a NumPy array?

I have encountered the following function in MATLAB that sequentially flips all of the dimensions in a matrix:

function X=flipall(X)
    for i=1:ndims(X)
        X = flipdim(X,i);
    end
end

Where X has dimensions (M,N,P) = (24,24,100). How can I do this in Python, given that X is a NumPy array?

like image 774
Wajih Avatar asked Sep 15 '16 05:09

Wajih


People also ask

How do you flip an element in a NumPy array?

The numpy. flip() function reverses the order of array elements along the specified axis, preserving the shape of the array. Parameters : array : [array_like]Array to be input axis : [integer]axis along which array is reversed.

How do you horizontally flip a NumPy array?

You can flip the image vertically and horizontally by using numpy. flip() , numpy. flipud() , numpy. fliplr() .

How do I reverse the order of rows in NumPy?

An array object in NumPy is called ndarray, which is created using the array() function. To reverse column order in a matrix, we make use of the numpy. fliplr() method. The method flips the entries in each row in the left/right direction.

How do I reverse a NumPy array from right to left?

Numpy: fliplr() function The fliplr() function is used to flip array in the left/right direction. Flip the entries in each row in the left/right direction. Columns are preserved, but appear in a different order than before. Input array, must be at least 2-D.


1 Answers

The equivalent to flipdim in MATLAB is flip in numpy. Be advised that this is only available in version 1.12.0.

Therefore, it's simply:

import numpy as np

def flipall(X):
    Xcopy = X.copy()
    for i in range(X.ndim):
        Xcopy = np.flip(Xcopy, i)
     return Xcopy

As such, you'd simply call it like so:

Xflip = flipall(X)

However, if you know a priori that you have only three dimensions, you can hard code the operation by simply doing:

def flipall(X):
    return X[::-1,::-1,::-1]

This flips each dimension one right after the other.


If you don't have version 1.12.0 (thanks to user hpaulj), you can use slice to do the same operation:

import numpy as np

def flipall(X):
    return X[[slice(None,None,-1) for _ in X.shape]]
like image 163
rayryeng Avatar answered Oct 08 '22 19:10

rayryeng