[英]Numpy: Convert RGB flat array to matrix
我有一个数组包含图像中所有像素的RGB值。 假设一个4x4图像,阵列大小为48,其中前16个值是红色值,接下来的16个是绿色,后16个是蓝色:
[r0, r1, ..., r15, g0, g1, ..., g15, b0, b1, ..., b14, b15]
现在我想将这个数组转换为深度为3的4x4矩阵:
[[[r0, g0, b0], ..., [r3, g3, b3]],
...
[[r12, g12, b12], ..., [r15, g15, b15]]]
为此,我正在进行reshape
+ transpose
+ reshape
:
import matplotlib.pyplot as plt
N = 4
numpy.random.seed(0)
rrggbb = numpy.random.randint(0, 255, size=N*N*3, dtype='uint8')
imgmatrix = rrggbb.reshape((3, -1)).transpose().reshape((N, N, 3))
plt.imshow(imgmatrix)
plt.show()
有没有更有效/简短的方法呢? (即:重塑/转置较少)
这是一个少一步的选项:
rrggbb.reshape((3, N, N)).transpose((1,2,0))
(rrggbb.reshape((3, N, N)).transpose((1,2,0)) == imgmatrix).all()
# True
或者您可以使用np.moveaxis
将axis 0
移动到最后一个轴:
np.moveaxis(rrggbb.reshape((3, N, N)), 0, -1)
(np.moveaxis(rrggbb.reshape((3, N, N)), 0, -1) == imgmatrix).all()
#True
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.