replace elements of array in python

48 Views Asked by At

I can't correctly change the elements of arrays with slicing in python please help me!!

this is my code:

maxVal=np.max(gradIntensity2) 
thrGradIntensity=gradIntensity2.copy()
highThr=maxVal/5
lowThr=maxVal/40
indHT=np.argwhere(gradIntensity2>=(highThr))
indLT=np.argwhere(gradIntensity2<=(lowThr))
ind1=(lowThr)<gradIntensity2
ind2=gradIntensity2<(highThr)
ind3=ind1 & ind2
ind=np.argwhere(ind3)
thrGradIntensity[indHT]=1
thrGradIntensity[indLT]=0
thrGradIntensity[ind]=0.5
print(maxVal) #-----------------------------result= 425.9426808716647
print(highThr)#-----------------------------result= 85.18853617433294
print(lowThr) #------------------------------result= 10.648567021791617
print(np.max(thrGradIntensity)) #--------------result= 0.5
print((thrGradIntensity==0.5).all()) #---------------result= true

I expect that np.max(thrGradIntensity) == 1 but this doesn't happen why????? print((thrGradIntensity==0.5).all()) why is this true?! my thresholding isn't work.

1

There are 1 best solutions below

1
Michael Cao On BEST ANSWER

Using np.argwhere as indices for a 2D array will treat each coordinate pair as a pair of row indices, not (row, column).

Example:

test = np.array([[1, 2],
                [3, 4]])

where_3 = np.argwhere(test == 3)

print(where_3)
print(test[where_3])

Output:

[[1 0]]
[[[3 4]
  [1 2]]]

It correctly identifies [1, 0] as the correct indices, but using test[where_3] returns the 1-row and the 0-row.

You're better off just dropping the np.argwhere and just using the boolean masks.

maxVal=np.max(gradIntensity2) 
thrGradIntensity=gradIntensity2.copy()
highThr=maxVal/5
lowThr=maxVal/40
indHT=gradIntensity2>=(highThr)
indLT=gradIntensity2<=(lowThr)
ind1=(lowThr)<gradIntensity2
ind2=gradIntensity2<(highThr)
ind = ind1 & ind2
thrGradIntensity[indHT]=1
thrGradIntensity[indLT]=0
thrGradIntensity[ind]=0.5
print(maxVal) #-----------------------------result= 425.9426808716647
print(highThr)#-----------------------------result= 85.18853617433294
print(lowThr) #------------------------------result= 10.648567021791617
print(np.max(thrGradIntensity)) #--------------result= 0.5
print((thrGradIntensity==0.5).all()) #---------------result= true