转置(3,0,1,2)是什么意思?

2024-05-06 16:41:46 发布

您现在位置:Python中文网/ 问答频道 /正文

这是什么意思

data.transpose(3, 0, 1, 2)

另外,如果data.shape == (10, 10, 10),为什么我会得到ValueError: axes don't match array


Tags: datamatcharraytransposeshapedonvalueerror我会
3条回答

看看numpy.transpose

Use transpose(a, argsort(axes)) to invert the transposition of tensors when using the axes keyword argument.

Transposing a 1-D array returns an unchanged view of the original array.


例如

>>> x = np.arange(4).reshape((2,2))
>>> x
array([[0, 1],
       [2, 3]])
>>>
>>> np.transpose(x)
array([[0, 2],
       [1, 3]])

操作从(samplesrowscolumnschannels)转换为(sampleschannelsrowscols),可能是opencv到pytorch

让我用Python3来讨论

I use the transpose function in python as data.transpose(3, 0, 1, 2)

这是错误的,因为此操作需要4个维度,而您只提供3个维度(如(10,10,10))。可复制为:

>>> a = np.arange(60).reshape((1,4,5,3))
>>> b = a.transpose((2,0,1))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: axes don't match array

如果图像批次为1,则可以通过将(10,10,10)重塑为(1,10,10,10)来添加另一个维度。这可以通过以下方式实现:

w,h,c = original_image.shape #10,10,10
modified_img = np.reshape((1,w,h,c)) #(1,10,10,10)

what does it mean of 3, 0, 1, 2.

对于2D numpy数组,数组(矩阵)的transpose操作与名称所述的一样。但是对于像您这样的高维数组,它基本上是作为moveaxis工作的

>>> a = np.arange(60).reshape((4,5,3))
>>> b = a.transpose((2,0,1))
>>> b.shape
(3, 4, 5)
>>> c = np.moveaxis(a,-1,0)
>>> c.shape
(3, 4, 5)
>>> b
array([[[ 0,  3,  6,  9, 12],
        [15, 18, 21, 24, 27],
        [30, 33, 36, 39, 42],
        [45, 48, 51, 54, 57]],

       [[ 1,  4,  7, 10, 13],
        [16, 19, 22, 25, 28],
        [31, 34, 37, 40, 43],
        [46, 49, 52, 55, 58]],

       [[ 2,  5,  8, 11, 14],
        [17, 20, 23, 26, 29],
        [32, 35, 38, 41, 44],
        [47, 50, 53, 56, 59]]])
>>> c
array([[[ 0,  3,  6,  9, 12],
        [15, 18, 21, 24, 27],
        [30, 33, 36, 39, 42],
        [45, 48, 51, 54, 57]],

       [[ 1,  4,  7, 10, 13],
        [16, 19, 22, 25, 28],
        [31, 34, 37, 40, 43],
        [46, 49, 52, 55, 58]],

       [[ 2,  5,  8, 11, 14],
        [17, 20, 23, 26, 29],
        [32, 35, 38, 41, 44],
        [47, 50, 53, 56, 59]]])

显然,这两种方法都是一样的

相关问题 更多 >