gpt4 book ai didi

python - reshape 图像数组

转载 作者:行者123 更新时间:2023-11-28 21:48:28 26 4
gpt4 key购买 nike

我有 60000 个 train_images 作为形状 (28,28,60000) 矩阵引入。它是一个 numpy.ndarray。我想将它转换为一维图像数组,这意味着每个图像都表示为单行/数字数组,我想要 60000 个数组。换句话说,我想从 (28, 28, 60000) 到 (60000, 28*28)。在 python 中,它将是:

images_features = []
for image in images:
imageLine = []
for y in range(len(image)):
for x in range(len(image[0])):
imageLine.append(image[y][x])
images_features.append(imageLine)

我该怎么做?我怀疑我需要使用 reshape,但我无法弄清楚如何才能做到这一点。

这就是我获取图像的方式:

data = scipy.io.loadmat('train.mat')


images = data["train_images"]

所以“图像”就是我所说的数组。

有人向我建议:

“您可能需要更改轴或组合它们才能获得所需的功能。我建议也绘制它们以防图像横向结束。确保您勤于使用轴以避免那里出现更多问题。”

我不知道这里指的是什么“轴”,也不知道如何将上述内容考虑在内。

有人可以解释我需要做什么以及为什么吗? (它做什么)

最佳答案

由于这是通过 loadmat 实现的,因此 (28,28,60000) 的形状很有意义 - MATLAB 从最后一个索引开始迭代。

images.transpose()  # or images.T

重新排序轴,所以结果是 (60000,28,28)。最后两个维度可以结合 reshape

images.T.reshape(60000,28*28)
images.T.reshape(60000,-1) # short hand

很多人需要转置 28x28 图像,例如

images.transpose([2,0,1])  # instead of the default [2,1,0]

.T 与 MATLAB '(或 .')相同。

images 也可以是 order='F'


octave:38> images=reshape(1:30,2,3,5);
octave:39> save test.mat -v7 images
octave:40> images
images =

ans(:,:,1) =

1 3 5
2 4 6

ans(:,:,2) =

7 9 11
8 10 12
....

我选择了较小的测试维度,以便于区分不同的轴。

在 Ipython session 中:

In [15]: data=io.loadmat('test.mat')

In [16]: data
Out[16]:
{'__globals__': [],
'__header__': 'MATLAB 5.0 MAT-file, written by Octave 3.8.2, 2016-02-10 05:19:18 UTC',
'__version__': '1.0',
'images': array([[[ 1., 7., 13., 19., 25.],
[ 3., 9., 15., 21., 27.],
[ 5., 11., 17., 23., 29.]],

[[ 2., 8., 14., 20., 26.],
[ 4., 10., 16., 22., 28.],
[ 6., 12., 18., 24., 30.]]])}

In [18]: data['images'].T
Out[18]:
array([[[ 1., 2.],
[ 3., 4.],
[ 5., 6.]],

[[ 7., 8.],
[ 9., 10.],
[ 11., 12.]],
....
In [19]: data['images'].transpose([2,0,1])
Out[19]:
array([[[ 1., 3., 5.],
[ 2., 4., 6.]],

[[ 7., 9., 11.],
[ 8., 10., 12.]],
....
In [22]: data['images'].transpose([2,1,0]).reshape(5,-1)
Out[22]:
array([[ 1., 2., 3., 4., 5., 6.],
[ 7., 8., 9., 10., 11., 12.],
...

关于python - reshape 图像数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35302361/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com