numpy数组中不需要的额外维度

2024-09-24 00:32:30 发布

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

我打开了一个.fits图像:

scaled_flat1 = pyfits.open('scaled_flat1.fit')

scaled_flat1a = scaled_flat1[0].data

当我打印它的形状时:

print scaled_flat1a.shape

我得到以下信息:

(1, 1, 510, 765)

我想读一下:

(510,765)

我该如何摆脱之前的两个?


Tags: 图像信息dataopenfit形状printshape
2条回答

我假设scaled_flat1a是一个numpy数组?在这种情况下,它应该像reshape命令一样简单。

import numpy as np

a = np.array([[[[1, 2, 3],
                [4, 6, 7]]]])
print(a.shape)
# (1, 1, 2, 3)

a = a.reshape(a.shape[2:])  # You can also use np.reshape()
print(a.shape)
# (2, 3)

有一个名为^{}的方法可以满足您的需要:

Remove single-dimensional entries from the shape of an array.

Parameters

a : array_like
    Input data.
axis : None or int or tuple of ints, optional
    .. versionadded:: 1.7.0

    Selects a subset of the single-dimensional entries in the
    shape. If an axis is selected with shape entry greater than
    one, an error is raised.

Returns

squeezed : ndarray
    The input array, but with with all or a subset of the
    dimensions of length 1 removed. This is always `a` itself
    or a view into `a`.

例如:

import numpy as np

extra_dims = np.random.randint(0, 10, (1, 1, 5, 7))
minimal_dims = extra_dims.squeeze()

print minimal_dims.shape
# (5, 7)

相关问题 更多 >