How to Replace multiple pixels with each numbers in numpy?

I have two np-array and one list like this.

import numpy as np

x = np.array([[1,2,3],[4,5,6],[7,8,9]])
y = np.ones((3,3))
idx = [[1,1],[2,2]]
x
>>> array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])
y
>>> array([[1., 1., 1.],
       [1., 1., 1.],
       [1., 1., 1.]])

I would like to get z array like this.

z
>>> array([[1., 1., 1.],
       [1., 5., 1.],
       [1., 1., 9.]])

Like above z array, i would like to replace index index of y in idx with index index of x in idx by not using for-loop.

If I use for loop, I can do it like this.

for i in range(len(idx)): 
    y[idx[i][0]][idx[i][1]] = x[idx[i][0]][idx[i][1]] 

Actually, this is easy example, but I have bigger array, so if I use for-loop, this takes much time.

HOW TO DO?

Answer

Don’t use a for loop, it defeats one of the reasons to use NumPy — vectorized operations.

import numpy as np

x = np.array([[1,2,3],[4,5,6],[7,8,9]])
y = np.ones((3,3))

# Rows and columns to filter.
idx = np.array([[1,1],[2,2]]).T

# Copying desired elements of x to y.
y[tuple(idx)] = x[tuple(idx)]

Taking the transpose of index as NumPy expects you to pass a tuple of row indices and column indices (row_idx, col_idx), which in your case would be ([1, 1], [2, 2]).

Leave a Reply

Your email address will not be published. Required fields are marked *