簡體   English   中英

Numpy 從 array1 中取出連續的值,將它們放入 array2 中存儲在 array3 中的連續索引處

[英]Numpy take consecutive values from array1, put them into array2 at consecutive indexes stored in array3

我有一個名為 img_matrix 的 bgr 值數組,一個名為 new_img 的空數組,以及另一個告訴 img_matrix 中的每個像素值應該 go 到 new_img 中的索引的數組,稱為 img_index。 所以基本上:

for i, point in enumerate(img_index):
    x = point[0]
    y = point[1]
    new_img[y][x] = img_matrix[i]

我怎樣才能擺脫 for 循環並加快速度? 我確定有一個 numpy function 可以做到這一點。

-- 一些澄清 -- 我的最終目標是將 640x480 圖像從具有已知旋轉和位移的無人機上的相機投影到 z=0 平面上。 投影后,圖像變成 z=0 平面上的點網格,類似於梯形。 我正在嘗試將這些點“插入”到規則網格中。 所有其他方法都太慢(scipy.interpolate,使用 kd 樹的最近鄰居)所以我設計了另一種方法。 我將坐標“四舍五入”到我想要采樣的網格上最近的點,並將這些點的 rgb 值分配給它們排列的圖像矩陣 new_img。 如果沒有排隊,我希望 rgb 值全部為零。 如果多個點彼此重疊,任何一個都可以。

一個例子可能是

img_index = 
[[0, 0]
 [0, 1]
 [0, 1]
 [1, 1]]

img_matrix = 
[[1, 2, 3]
 [4, 5, 6]
 [7, 8, 9]
 [10, 11, 12]]

new_img=
[[[1,2,3],[7,8,9]]
 [[0,0,0],[10,11,12]]]

提前致謝!

似乎您想創建一個空數組並在特定位置填充其值。 你可以像這樣以矢量化的方式做到這一點:

img_index = np.array([[0, 0], [0, 1], [0, 1], [1, 1]])
img_matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]])
new_img = np.zeros(shape=(2, 2, 3), dtype=int)
new_img[img_index[:,0], img_index[:,1]] = img_matrix
new_img
>>>
array([[[ 1,  2,  3],
        [ 7,  8,  9]],

       [[ 0,  0,  0],
        [10, 11, 12]]])

暫無
暫無

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

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