我有一個 3D numpy 陣列data,其中尺寸a和b表示影像的解析度,c是影像/幀數。我想在維度np.histogram上呼叫每個像素(a和b組合),并使用c維度的輸出陣列(a, b, BINS)。我已經用嵌套回圈完成了這個任務,但是我怎樣才能向量化這個操作呢?
hists = np.zeros((a, b, BINS))
for row in range(a):
for column in range(b):
hists[row, column, :] = np.histogram(data[row, column, :], bins=BINS)[0]
我相信該解決方案是微不足道的,但感謝所有幫助:)
uj5u.com熱心網友回復:
np.histogram在展平的陣列上進行計算。但是,您可以使用np.apply_along_axis.
np.apply_along_axis(lambda a: np.histogram(a, bins=BINS)[0], 2, data)
uj5u.com熱心網友回復:
這是一個有趣的問題。
制作一個最小的作業示例(MWE)
這應該是在 SO 上提問的主要習慣。
a, b, c = 2, 3, 4
data = np.random.randint(10, size=(a, b, c))
hists = np.zeros((a, b, c), dtype=int)
for row in range(a):
for column in range(b):
hists[row, column, :] = np.histogram(data[row, column, :], bins=c)[0]
data
>>> array([[[6, 4, 3, 3],
[7, 3, 8, 0],
[1, 5, 8, 0]],
[[5, 5, 7, 8],
[3, 2, 7, 8],
[6, 8, 8, 0]]])
hists
>>> array([[[2, 1, 0, 1],
[1, 1, 0, 2],
[2, 0, 1, 1]],
[[2, 0, 1, 1],
[2, 0, 0, 2],
[1, 0, 0, 3]]])
讓它盡可能簡單(但仍然有效)
您可以消除一個回圈并簡化它:
new_data = data.reshape(a*b, c)
new_hists = np.zeros((a*b, c), dtype=int)
for row in range(a*b):
new_hists[row, :] = np.histogram(new_data[row, :], bins=c)[0]
new_hists
>>> array([[2, 1, 0, 1],
[1, 1, 0, 2],
[2, 0, 1, 1],
[2, 0, 1, 1],
[2, 0, 0, 2],
[1, 0, 0, 3]])
new_data
>>> array([[6, 4, 3, 3],
[7, 3, 8, 0],
[1, 5, 8, 0],
[5, 5, 7, 8],
[3, 2, 7, 8],
[6, 8, 8, 0]])
你能找到類似的問題并使用他們解決方案的關鍵點嗎?
通常,您不能對回圈中進行的類似操作進行矢量化:
for row in array:
some_operation(row)
除了您可以在扁平陣列上呼叫另一個矢量化操作然后將其移回初始形狀的情況外:
arr = array.ravel()
another_operation(arr)
out = arr.reshape(array.shape)
看起來你很幸運,np.histogram因為我很確定以前也做過類似的事情。
最終解決方案
new_data = data.reshape(a*b, c)
m, M = new_data.min(axis=1), new_data.max(axis=1)
bins = (c * (new_data - m[:, None]) // (M-m)[:, None])
out = np.zeros((a*b, c 1), dtype=int)
advanced_indexing = np.repeat(np.arange(a*b), c), bins.ravel()
np.add.at(out, advanced_indexing, 1)
out.reshape((a, b, -1))
>>> array([[[2, 1, 0, 0, 1],
[1, 1, 0, 1, 1],
[2, 0, 1, 0, 1]],
[[2, 0, 1, 0, 1],
[2, 0, 0, 1, 1],
[1, 0, 0, 1, 2]]])
請注意,它在每個直方圖中添加了一個額外的 bin 并在其中放置了最大值,但我希望如果您需要修復它并不難。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/384726.html
