Home > Mobile >  Numpy: How to find the ratio between multiple channels and assign index of a particular channel if i
Numpy: How to find the ratio between multiple channels and assign index of a particular channel if i

Time:11-25

I have numpy array(Dimension : N * X * Y) of N channels. I need to find the ratio for each X,Y between the N channels. Create a new array (Dimension : X * Y) and assign the index of a particular channel (say N =1) if its ratio is greater than a threshold value else assign the maximum value index. Say there are 2 channels and if ratio of X,Y point of channel 1 is greater than 0.3, I need to assign 1 to the (X,Y) of new array, if less than 0.4 then assign the max channel index. Please advise, Thanks.

CodePudding user response:

channel1 = arr[0, :, :] will get the values in channel 1 as an X by Y array. channel2 = arr[1, :, :] will get the values in channel 2. Then channel1 / channel2 > 0.4 will give you an X by Y array with True in any spot where the ratio is more than 0.4. You can convert this to int to get 1s and 0s.

CodePudding user response:

I used the below code to solve the problem.

import numpy as np

#N * X * Y  => 3 * 2 * 3
inputArray = np.array([[[1,1,1],
                    [1,1,1]],
                    [[1,2,1],
                    [1,2,1]],
                    [[3,3,3],
                    [3,3,3]]])

#Get the ratio
ratio = inputArray / inputArray .sum(axis=0)
print(ratio)
# Create result array
result = np.zeros((2,3))
#Check if ratio of Channel N =1 > threshold value 0.3, if true assign 1 else assign channel index of maximum ratio.  
result[:,:] = np.where(ratio[1,:,:] > 0.3, 1 ,np.argmax(ratio, axis=0))

print(result)

------------------------------
>ratio:

  [[[0.2        0.16666667 0.2       ]
    [0.2        0.16666667 0.2       ]]
   [[0.2        0.33333333 0.2       ]
    [0.2        0.33333333 0.2       ]]
   [[0.6        0.5        0.6       ]
    [0.6        0.5        0.6       ]]]

> result:

 [[2. 1. 2.]
   [2. 1. 2.]]
  • Related