簡體   English   中英

在python中,如何使用np數組有效地處理多維?

[英]In python, how to use np array to manipulate multi-dimension efficiently?

我的數據集中有成千上萬的32 X 32 RGB圖像。 例如。

X_train,形狀(123123、32、32、3)

我想將rgb變灰,並將形狀更改為(123123,32,32,1)

我這里的代碼非常不夠,我想知道什么是最好的方法。 我在AWS G2或P2主機上,所以我有GPU。

謝謝。

def grayedOut(x) :
    out = []

    for n in range(len(x)) :
        nv = []
        for i in range(len(x[n])) :
            iv = []
            for j in range(len(x[n,i])) :
                r,g,b = x[n,i,j,0], x[n,i,j,1], x[n, i,j,2]
                gray = np.uint8(0.2989 * r + 0.5870 * g + 0.1140 * b)

                iv.append(np.asarray([gray]))
            nv.append(iv)
        out.append(nv)
    return np.asarray(out)

你可以簡單地寫

def grayedOut(x):
    return x.dot([0.2989, 0.5870, 0.1140])[..., np.newaxis].astype(np.uint8) 
  • x.dot([0.2989, 0.5870, 0.1140]) :計算每個像素的灰度分量。 結果形狀將為(123123, 32, 32)
  • [..., np.newaxis] :為結果創建一個新軸,並給出所需的形狀(123123, 32, 32, 1)
  • .astype(np.uint8) :將數據類型轉換為uint8。

假設images所有 RGB圖像的數組。 然后,以下代碼生成灰度圖像數組:

coeffs = np.array([0.2989, 0.5870, 0.1140])
gray = np.apply_along_axis(coeffs.dot, 3, images).astype(np.uint8)

我希望這段代碼比您的三重循環更快。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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