這是我的代碼:
# 'a' is a 3D array which is the RGB data
a = np.array([[[1, 2, 3], [4, 5, 6]], [[4, 5, 6], [1, 2, 3]]])
# I want to do some calculate separately on R, G and B
np.apply_along_axis(lambda r, g, b: r * 0.5 g * 0.25 b * 0.25, axis=-1, arr=a)
# my target output is: [[1.75, 4.75], [4.75, 1.75]]
但是上述方法會給我錯誤,缺少 2 個必需的位置引數。
我試圖這樣做:
np.apply_along_axis(lambda x: x[0] * 0.5 x[1] * 0.25 x[2] * 0.25, axis=-1, arr=a)
它可以作業,但是每次我需要對陣列元素進行計算時,我都需要鍵入索引,這是非常多余的。有什么方法可以在使用 np.apply_along_axis 時將陣列軸作為多 iuputs 傳遞給 lambda?
uj5u.com熱心網友回復:
apply_along_axis 緩慢且不必要:
In [279]: a = np.array([[[1, 2, 3], [4, 5, 6]], [[4, 5, 6], [1, 2, 3]]])
In [280]: r,g,b = a[...,0],a[...,1],a[...,2]
...: r * 0.5 g * 0.25 b * 0.25
Out[280]:
array([[1.75, 4.75],
[4.75, 1.75]])
或者
In [281]: a.dot([0.5, 0.25, 0.25])
Out[281]:
array([[1.75, 4.75],
[4.75, 1.75]])
或者
In [282]: np.sum(a*[0.5, 0.25, 0.25], axis=2)
Out[282]:
array([[1.75, 4.75],
[4.75, 1.75]])
uj5u.com熱心網友回復:
in 函式apply_along_axis接受一個引數。
您需要使用:
np.apply_along_axis(lambda x: x[0] * 0.5 x[1] * 0.25 x[2] * 0.25, axis=-1, arr=a)
輸出:
array([[1.75, 4.75],
[4.75, 1.75]])
也就是說,您也可以直接執行操作:
(a*np.array([0.5, 0.25, 0.25])).sum(2)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/361974.html
