簡體   English   中英

Numpy:將RGB平面陣列轉換為矩陣

[英]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.moveaxisaxis 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM