Home > Net >  Python numpy: Simplify operation on multiple matrices
Python numpy: Simplify operation on multiple matrices

Time:02-04

I have 3 numpy matrices:

One contains pixels positions in X (x_pos), another pixel positions in Y (y_pos) and a last one containing pixel values (p_value)

I would like to use these 3 matrices to build a results image

With loops I have this result:

#Resulting image
res = np.zeros((128,128,3), dtype = np.uint8)

for i in range(x_pos.shape[0]):
    for j in range(x_pos.shape[1]):

        # Get coordinates
        x = x_pos[i][j]
        y = y_pos[i][j]
            
        res[y,x] = p_value[i][j]

With large matrices (2048*2048) this code already takes a lot of time. Is it possible to optimize this code without using a nested loop?

I specify that the positions in the pos_x and pos_y matrices do not necessarily follow each other, there may be holes or duplicate values

CodePudding user response:

You could take a look into sparse matrices: Scipy Sparse Matrix Documentation

CodePudding user response:

is there any correlation between the 3 lists (x_pos, y_pos, p_value) about the index of the information about arbitrary pixel x?

CodePudding user response:

First use consistent numpy 2d array indexing:

    x = x_pos[i,j]
    y = y_pos[i,j]    
    res[y,x] = p_value[i,j]

Now instead of scalar i,j use arrays

 i = np.arange(n); j = np.arange(m)

You didn't provida [mcve] so I won't try to demonstrate that th

  •  Tags:  
  • Related