简体   繁体   中英

What is the most efficient way to Normalize a 4D array?

I have a 4D array with shape (4, 320, 528, 279) which in fact is a data set of 4, 3D image stacks.

What I am trying to achieve is to normalize each pixel of each 3D image between all the samples. So let's say the first pixel values with coordinates (0,0,0) in the four images are [140., 20., 10., 220.]. I would like to change those values so that they become: [0.61904762, 0.04761905, 0., 1.].

I wrote a script that supposedly achieves this:

def NormalizeMatrix(mat) :

    mat = np.array(mat);
    sink = mat.copy();

    for i in np.arange(mat.shape[1]) :

        for j in np.arange(mat.shape[2]) :

            for k in np.arange(mat.shape[3]) :

                PixelValues = mat[:,i,j,k];
                Min = float(PixelValues.min());
                Max = float(PixelValues.max());

                if Max-Min != 0. :

                    sink[:,i,j,k] = (PixelValues - Min) / (Max - Min);

                else :

                    sink[:,i,j,k] = np.full_like(PixelValues, 0.);

    return sink;

But this is really REALLY slow !

How can I make this faster?

Any ideas?

Tom

I think I found a pretty fast way in the end which actually goes in the way of user3483203:

def NormalizeMatrix(mat) :

    mat = np.array(mat);
    minMat = np.min(mat, axis=0, keepdims=1);
    maxMat = np.max(mat, axis=0, keepdims=1);

    sink = (mat - minMat)/ (maxMat - minMat);

    return sink;

This takes 5-10s instead of hours on my machine:)

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