简体   繁体   中英

Pass arguments of 3D numpy array into a 4D numpy array

I want to sort a 4D numpy array by the result of an numpy.argsort evaluated on a reduced 3D version of that array. Something like this:

array.shape
    (7, 3178, 3178, 3)
array_reduced.shape
    (7, 3178, 3178)
args=numpy.argsort(array_reduced,axis=0)
array_sorted=array[args,:]

This returns a memory error:

    ---------------------------------------------------------------------------
    MemoryError                               Traceback (most recent call last)
    <ipython-input-48-04f432d9e05d> in <module>()
          ----> 1 array_sorted=array[args,:]

    MemoryError:

This may be a stupid mistake about how to cast lambda functions, but if someone could help me I would really appreciate it!

-------------------------------------- EDIT -----------------------

This code does what I want it to do but it is v slow:

array_sorted=np.zeros(array.shape,dtype=np.uint8)
for thet in range (0, array.shape[0]):
    print(thet)
    for y in range (0, array.shape[1]):
        for x in range (0, array.shape[2]):
            array_sorted[thet,y,x,0]=(array[args[thet,y,x],y,x,0])
            array_sorted[thet,y,x,1]=(array[args[thet,y,x],y,x,1])
            array_sorted[thet,y,x,2]=(array[args[thet,y,x],y,x,2])

You can vectorize your loop using np.ogrid :

i,j,k = np.ogrid[tuple(map(slice, array.shape[:-1]))]
array_sorted = array[args, j, k]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM