Numpy:将RGB平面阵列转换为矩阵

2024-05-12 22:49:10 发布

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

我有一个数组包含图像中所有像素的RGB值。假设4x4图像,数组大小为48,其中前16个值为红色值,后16个值为绿色,最后16个值为蓝色:

[r0, r1, ..., r15, g0, g1, ..., g15, b0, b1, ..., b14, b15]

现在,我想将该数组转换为深度为3的4x4矩阵,格式如下:

^{pr2}$

为此,我要做一个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()

enter image description here

有没有更有效/更短的方法?(即:较少的整形/换位)


Tags: 图像numpypltrandomrgb像素数组蓝色
1条回答
网友
1楼 · 发布于 2024-05-12 22:49:10

以下是一个无需一步操作的选项:

rrggbb.reshape((3, N, N)).transpose((1,2,0))
​
(rrggbb.reshape((3, N, N)).transpose((1,2,0)) == imgmatrix).all()
# True

或者可以使用np.moveaxisaxis 0移到最后一个轴:

^{pr2}$

相关问题 更多 >