图像扁平化时,为何numpy.reshape(4,2)与reshape(2,4).T结果不同?
为什么直接
reshape(4,2)无法得到预期的扁平化结果? 现有一个形状为(2, 2, 2)的NumPy数组:
import numpy as np arr = np.array([[[1, 2], [3, 4]], [[1, 2], [3, 4]]]) print(arr.shape) # 输出 (2, 2, 2)
需求是将其重塑为4×2的数组,要求每一列对应一张扁平化后的图像,预期结果为:
[[1 1] [2 2] [3 3] [4 4]]
两种重塑方法的差异
1. 使用.reshape(2, 4).T得到预期结果
arr_flatten = arr.reshape(2, 4).T print(arr_flatten) # 输出: # [[1 1] # [2 2] # [3 3] # [4 4]]
2. 使用.reshape(4, 2)未得到预期结果
arr_flatten = arr.reshape(4, 2) print(arr_flatten) # 输出: # [[1 2] # [3 4] # [1 2] # [3 4]]
原因解析
NumPy的reshape默认遵循**行优先(C风格)**的元素读取顺序:即先遍历最内层的维度,再依次向外层推进。
我们先拆解原数组的元素存储顺序(按行优先展开后的一维序列):
原数组包含2个(2,2)的子数组(对应两张图像):
- 第一张图像:
[[1,2],[3,4]]→ 按行优先展开为[1,2,3,4] - 第二张图像:
[[1,2],[3,4]]→ 按行优先展开为[1,2,3,4]
整个数组的一维展开序列是:[1,2,3,4,1,2,3,4]
调用
reshape(4,2)时,NumPy会把这个一维序列按行优先填充到4×2的数组中:
第一行取前2个元素 →[1,2],第二行取接下来2个 →[3,4],第三行取[1,2],第四行取[3,4],这就是你看到的非预期结果。调用
reshape(2,4)时,一维序列会被填充为2×4的数组:[[1,2,3,4], [1,2,3,4]]再转置(
.T)后,就把每一列的元素对应到了两张图像的相同位置,最终得到符合需求的4×2数组。
如果想直接用reshape得到预期结果,可以指定**列优先(Fortran风格)**的顺序:
arr_flatten = arr.reshape(4, 2, order='F') print(arr_flatten) # 输出: # [[1 1] # [2 2] # [3 3] # [4 4]]
内容的提问来源于stack exchange,提问作者Magnus Sesodia
相关产品推荐
相关产品推荐

