Search code examples
imageconditional-statementsshapesimshow

How to extract specific condition values in python np.array without changing the shape


Range value of my image data is -0.3 ~ 28.25 and image shape was like this.

D1 = data1
D1 = D1[0, 0, ...]

D1 = data1 -> shape : (1,1,512,512)

D1 = D1[0, 0, ...] -> shape: (512,512)

Because, I only want to use data for (max value of data)*0.05 ~ (max value of data), I did like this

D1_ex = np.extract(D1>np.max(D1)*0.05, D1)

but then the shape of this image is (60304,).

At this point, if I don't want to lose the original position of each value, because I'm trying to see the image which satisfies the condition,1

I wonder if there is any good way to solve this situation.


Solution

  • To get a new array with the same shape than the original, np.extract is not useful because, as you have seen, it returns an 1D array.

    You could create a mask (boolean array) by directly saving the result of comparing the array with the threshold. Then, you may create a new zero-array with the same shape than the original array and copy the values where mask is True.

    As an example, I have created a random 3x3 array and applied the threshold you have described:

    >>> import numpy as np
    
    >>> D1 = np.random.rand(3,3)
    >>> D1
    array([[0.3641107 , 0.9289969 , 0.34805294],
           [0.95106249, 0.75310846, 0.49631097],
           [0.5286944 , 0.0044787 , 0.30546521]])
    
    >>> threshold = np.max(D1)*0.05 # Calculate the threshold
    >>> threshold
    0.047553124492556255
    
    >>> mask = D1 > threshold # Create the mask
    >>> mask
    array([[ True,  True,  True],
           [ True,  True,  True],
           [ True, False,  True]])
    
    >>> new_D1 = np.zeros(D1.shape) # Create the zero-array
    >>> new_D1[mask] = D1[mask] # Copy the interesting values
    >>> new_D1
    array([[0.3641107 , 0.9289969 , 0.34805294],
           [0.95106249, 0.75310846, 0.49631097],
           [0.5286944 , 0.        , 0.30546521]])
    

    As you can see, new_D1 has the same values that the original D1 where mask is True, and 0 otherwise.

    If you wish to copy the code more conveniently, here there is the version without the results:

    import numpy as np
    
    D1 = np.random.rand(3,3)
    
    # Calculate the threshold
    threshold = np.max(D1)*0.05
    
    # Create the mask
    mask = D1 > threshold
    
    # Create the zero-array
    new_D1 = np.zeros(D1.shape)
    # Copy the interesting values
    new_D1[mask] = D1[mask]