Steffeny
Steffeny

Reputation: 17

How to apply threshold to image

I have an image and would like to use the thresholding to reduce its noise. I try to flatten its grid into 1D array, and then would like to use 0 to replace the pixel’s actual intensity if it is below the threshold, finally reshape it into the original grid. Here is my code:

Threshold_flat = np.array(Threshold_flat)
Threshold = Threshold_flat.flatten()

Threshold_1 = []
for i in range(len(Threshold)):           
        x = [i if i>20 else 0 for i in Threshold]        
        Threshold_1.append(x)
        
Threshold_1 = np.array(Threshold_1)
Threshold_1 = Threshold_1.reshape(326,481) 

But it doesn't work when I run the code, and the processing is also very slow.

I am confused about it and have no idea how to resolve it.

Thanks in advance for any help!

Upvotes: 0

Views: 119

Answers (1)

Carlos Melus
Carlos Melus

Reputation: 1552

np.where does exactly what you're looking for:

output = np.where(Threshold > 20, Threshold, 0)

Upvotes: 1

Related Questions