无法将3维NumPy数组重塑为2维NumPy数组 [英] Trouble reshaping 3-d NumPy array into 2-d NumPy array

查看:58
本文介绍了无法将3维NumPy数组重塑为2维NumPy数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理图像处理问题,我的数据显示为3维NumPy数组,其中(x,y,z)项是(x,y)像素(数字强度值)图片z.有100000张图像,每个图像为25x25.因此,数据矩阵的大小为25x25x10000.我正在尝试将其转换为大小为10000x625的二维矩阵,其中每一行都是图像中像素的线性化.例如,假设图像是3x3,我们将具有以下内容:

I'm working on a problem with image processing, and my data is presented as a 3-dimensional NumPy array, where the (x, y, z) entry is the (x, y) pixel (numerical intensity value) of image z. There are 100000 images and each image is 25x25. Thus, the data matrix is of size 25x25x10000. I am trying to convert this into a 2-dimensional matrix of size 10000x625, where each row is a linearization of the pixels in the image. For example, suppose that instead the images were 3x3, we would have the following:

1 2 3
4 5 6  ------> [1, 2, 3, 4, 5, 6, 7, 8, 9]
7 8 9

我正在尝试通过调用 data.reshape((10000,625))来做到这一点,但是这样做之后数据不再正确对齐.我曾尝试在重塑的有效阶段对矩阵进行转置,但这似乎无法解决问题.

I am attempting to do this by calling data.reshape((10000, 625)), but the data is no longer aligned properly after doing so. I have tried transposing the matrix in valid stages of reshaping, but that does not seem to fix it.

有人知道如何解决此问题吗?

Does anyone know how to fix this?

推荐答案

问题是您没有在 reshape 调用中遵守标准索引顺序.仅当要合并的两个维度在新数组中的相同位置((25,25,10000)-> (625,10000)).

The problem is that you aren't respecting the standard index order in your reshape call. The data will only be aligned if the two dimensions you want to combine are in the same position in the new array ((25, 25, 10000) -> (625, 10000)).

然后,要获得所需的形状,可以进行转置.使用较小的示例可以更轻松地实现可视化-遇到此类问题时,请尽可能在REPL中尝试较小的示例.

Then, to get the shape you want, you can transpose. It's easier to visualize with a smaller example -- when you run into problems like this, always try out a smaller example in the REPL if you can.

>>> a = numpy.arange(12)
>>> a = a.reshape(2, 2, 3)
>>> a
array([[[ 0,  1,  2],
        [ 3,  4,  5]],

       [[ 6,  7,  8],
        [ 9, 10, 11]]])
>>> a.reshape(4, 3)
array([[ 0,  1,  2],
       [ 3,  4,  5],
       [ 6,  7,  8],
       [ 9, 10, 11]])
>>> a.reshape(4, 3).T
array([[ 0,  3,  6,  9],
       [ 1,  4,  7, 10],
       [ 2,  5,  8, 11]])

无需 rollaxis

请注意 numpy 使用的打印布局如何使这种推理更加容易.第一步和第二步之间的区别只是在括号位置 ;这些数字都位于同一位置,这在您需要考虑形状问题时通常会有所帮助.

Notice how the print layout that numpy uses makes this kind of reasoning easier. The differences between the first and the second step are only in the bracket positions; the numbers all stay in the same place, which often helps when you want to think through shape issues.

这篇关于无法将3维NumPy数组重塑为2维NumPy数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆