简体   繁体   English

你如何顺序翻转NumPy数组中的每个维度?

[英]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: 我在MATLAB中遇到了以下函数,它顺序翻转矩阵中的所有维度:

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) . 其中X尺寸(M,N,P) = (24,24,100) How can I do this in Python, given that X is a NumPy array? 考虑到X是NumPy数组,我怎样才能在Python中执行此操作?

The equivalent to flipdim in MATLAB is flip in numpy . 等效flipdim在MATLAB是flipnumpy Be advised that this is only available in version 1.12.0. 请注意,这仅适用于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: 如果您没有版本1.12.0(感谢用户hpaulj),您可以使用slice执行相同的操作:

import numpy as np

def flipall(X):
    return X[[slice(None,None,-1) for _ in X.shape]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM