numpy2dnumpy-indexing

manipulating a numpy array with another array


I am doing my head in with brackets and ':' whilst trying to do 2 dimensional indexing with an other index So I would be really pleased if somebody could straighten me out

I have an greyscale image BlurredFlip shape is : (480, 640) then I have used

minCoords = np.argmin(BlurredFlip, axis=0)

which has created a 1D array with, no surprise, the first row that has the minimum value for each column eg

minCoords = [292 289 289 287 287 .......

now I want to set to black every pixel beyond this row value - without using loops in python the equivalent of

    BlurredFlip[292:479, 0] = 0
    BlurredFlip[289:479, 1] = 0
    BlurredFlip[289:479, 2] = 0
    BlurredFlip[287:479, 3] = 0

  and so on. 

in pseudo code

for col in 1 to maxcol
   BlurredFlip[minCoords[col]:imageheight, col] = 0  

I cant seem to get a way to reference the column twice like that. But I can tell you many many ways to get the useless error "TypeError: only integer scalar arrays can be converted to a scalar index"

Thanks for any enlightenment :)


Solution

  • I think I found a solution without using a for-loop. It might save you time, but not storage, if that is an issue. Given a 2D array A and a 1D array row. The dimension of row is the number of columns of A. For column i we set entries whose row number is greater than row[i] to zero. Consider the following code:

    import numpy as np
    AA  = np.arange(16).reshape(4,4)+1;
    row = np.asarray([0,1,2,3]);
    rowidx, colidx = np.indices(AA.shape);
    rowmask = rowidx > row;
    AA[rowmask] = 0;
    

    The output is

    AA = array([[ 1,  2,  3,  4],
           [ 0,  6,  7,  8],
           [ 0,  0, 11, 12],
           [ 0,  0,  0, 16]])
    

    The lower triangular part of the 2D array AA has been set to zero. The magic happens in the line rowmask = rowidx > row, which creates the mask. The rest is straight forward.

    For your case, the solution is

    rowidx,colidx = np.indices(BlurredFlip)
    rowmask = rowidx > minCoords
    BlurredFlip[rowmask] = 0