Home > Net >  Numpy take consecutive values from array1, put them into array2 at consecutive indexes stored in arr
Numpy take consecutive values from array1, put them into array2 at consecutive indexes stored in arr

Time:02-11

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. 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? Im sure there's a numpy function that does this.

--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. After projection, the image turns into a grid of points on the z=0 plane resembling a trapezoid. I am trying to "interpolate" these points onto a regular grid. All other methods were too slow (scipy.interpolate, nearest neighbor using k-d tree) so i devised another method. 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. If nothing lines up, i would like the rgb values to all be zero. 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!

CodePudding user response:

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]]])
  • Related