简体   繁体   English

Numpy 从 array1 中取出连续的值,将它们放入 array2 中存储在 array3 中的连续索引处

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

I have an array of bgr values called img_matrix, an empty array called new_img, and another array that tells what index every pixel value in img_matrix should go to in new_img, called img_index.我有一个名为 img_matrix 的 bgr 值数组,一个名为 new_img 的空数组,以及另一个告诉 img_matrix 中的每个像素值应该 go 到 new_img 中的索引的数组,称为 img_index。 So basically:所以基本上:

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

How can i get rid of the for loop and speed things up?我怎样才能摆脱 for 循环并加快速度? Im sure there's a numpy function that does this.我确定有一个 numpy function 可以做到这一点。

--some clarification-- my end goal is projecting a 640x480 image from a camera on a drone with a known rotation and displacement, onto the z=0 plane. -- 一些澄清 -- 我的最终目标是将 640x480 图像从具有已知旋转和位移的无人机上的相机投影到 z=0 平面上。 After projection, the image turns into a grid of points on the z=0 plane resembling a trapezoid.投影后,图像变成 z=0 平面上的点网格,类似于梯形。 I am trying to "interpolate" these points onto a regular grid.我正在尝试将这些点“插入”到规则网格中。 All other methods were too slow (scipy.interpolate, nearest neighbor using kd tree) so i devised another method.所有其他方法都太慢(scipy.interpolate,使用 kd 树的最近邻居)所以我设计了另一种方法。 I "round" the coordinates into the closest point on the grid i want to sample, and assign the rgb values of those points to the image matrix new_img where they line up.我将坐标“四舍五入”到我想要采样的网格上最近的点,并将这些点的 rgb 值分配给它们排列的图像矩阵 new_img。 If nothing lines up, i would like the rgb values to all be zero.如果没有排队,我希望 rgb 值全部为零。 If multiple points line up on top of each other, any will do.如果多个点彼此重叠,任何一个都可以。

an example would maybe be一个例子可能是

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]]]

Thanks in advance!提前致谢!

It seems that you want to create an empty array and fill its values at the specific places.似乎您想创建一个空数组并在特定位置填充其值。 You could do it in a vectorised way like so:你可以像这样以矢量化的方式做到这一点:

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