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?
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.
You can flip the image vertically and horizontally by using numpy. flip() , numpy. flipud() , numpy. fliplr() .
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.
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.
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]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With