我有一個存盤為 3 個 Numpy 陣列的影像:
# Int arrays of coordinates
# Not continuous, some points are omitted
X_image = np.array([1,2,3,4,5,6,7,9])
Y_image = np.array([9,8,7,6,5,4,3,1])
# Float array of RGB values.
# Same index
rgb = np.array([
[0.5543,0.2665,0.5589],
[0.5544,0.1665,0.5589],
[0.2241,0.6645,0.5249],
[0.2242,0.6445,0.2239],
[0.2877,0.6425,0.5829],
[0.5543,0.3165,0.2839],
[0.3224,0.4635,0.5879],
[0.5534,0.6693,0.5889],
])
RGB 資訊不可轉換為 int。所以它必須保持浮動
我有另一個陣列,用于定義影像中某些像素區域的位置:
X_area = np.array([3,4,6])
Y_area = np.array([7,6,4])
我需要找到這些像素的 RGB 資訊,使用前 4 個陣列作為參考。
我的想法是在整個影像中搜索這些區域點的索引,然后使用這個索引來找回RGB資訊。
index = search_for_index_of_array_1_in_array_2((X_area,Y_area),(X_image,Y_image))
# index shall be [3,4,6]
rgb_area = rgb[index]
search_for_index_of_array_1_in_array_2 可以用 for 回圈實作。我試過了,這太慢了。我實際上有數百萬積分。
我知道它可能更像是 Julia 的用例而不是 Python,因為我們處理具有性能需求的低級資料操作,但我不得不使用 Python。所以,我看到的唯一性能技巧是使用 NumPy 的矢量化解決方案。
我不習慣操縱 NumPy。我試過numpy.where。
index = np.where(X_area in X_image and Y_area in Y_image )
index
給出:
<ipython-input-18-0e434ab7a291>:1: DeprecationWarning: elementwise comparison failed; this will raise an error in the future.
index = np.where(X_area in X_image and Y_area in Y_image )
(array([], dtype=int64),)
它應該是空的,因為我們有 3 個合規點。
我也測驗過,結果相同:
XY_image = np.vstack((X_image,Y_image))
XY_area = np.vstack((X_area,Y_area))
index = np.where(XY_area == XY_image)
乃至:
np.extract(XY_image == XY_area, XY_image)
如果我明白了,問題是陣列的長度不同。但這就是我所擁有的。
你知道如何進行嗎?
謝謝
編輯:這是一個有效的回圈,但......速度不快:
indexes = []
for i in range(XY_area.shape[1]):
XY_area_b = np.broadcast_to(XY_area[:,i],(9,2)).transpose()
where_in_image = np.where(XY_area_b == XY_image)
index_in_image = where_in_image[1][1]
indexes.append(index_in_image)
indexes
uj5u.com熱心網友回復:
解決這個問題的經典方法通常是使用hashmap。但是,Numpy 沒有提供這樣的資料結構。話雖如此,另一種(通常較慢)的解決方案是對值進行排序,然后執行二分搜索。希望 Numpy 提供有用的函式來做到這一點。此解決方案運行O(n log(m))(具有n要搜索的值m的數量和搜索的值的數量)應該比O(n m)及時運行的線性搜索快得多。下面是一個例子:
# Format the inputs
valType = X_image.dtype
assert Y_image.dtype == valType and X_area.dtype == valType and X_image.dtype == valType
pointType = [('x', valType),('y', valType)]
XY_image = np.ravel(np.column_stack((X_image, Y_image))).view(pointType)
XY_area = np.ravel(np.column_stack((X_area, Y_area))).view(pointType)
# Build an index to sort XY_image and then generate the sorted points
sortingIndex = np.argsort(XY_image)
sorted_XY_image = XY_image[sortingIndex]
# Search each value of XY_area in XY_image and find the location in the unsorted array
tmp = np.searchsorted(XY_image, XY_area)
index = sortingIndex[tmp]
rgb_area = rgb[index]
uj5u.com熱心網友回復:
感謝 Jér?me 的回答,我更好地理解了使用哈希圖的價值:
def hashmap(X,Y):
return X 10000*Y
h_area = hashmap(X_area,Y_area)
h_image = hashmap(X_image,Y_image)
np.where(np.isin(h_image,h_area))
這個哈希圖有點殘酷,但它實際上回傳了索引:
(array([2, 3, 5], dtype=int64),)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/369775.html
上一篇:這個陣列是否有不可呼叫的原因?
