griffinc griffinc - 2 months ago 15
Python Question

Replace numbers below threshold # in numpy array with zeroes

So I have a very big Numpy array (2560x1920). Its actually from a grayscale picture where every pixel is given a number from 0-1 indicating its brightness.

I'm trying to replace all values below a threshold, say 0.5, with zeroes.
This is probably a simple task but I'm a beginner with Numpy and I've searched around and still can't figure it out.

This is what I've attempted and I know its wrong...

for x in np.nditer(Image):
if x < .5:
x == 0

plt.imshow(Image, cmap=plt.cm.gray)
plt.show()


It just outputs the normal image without changing anything.

Also the array looks something like this (abbreviated obviously):

[[ 0.24565263 0.24565263 0.24902149 ..., 0.27528678 0.27265316
0.27606536]
[ 0.24565263 0.24565263 0.24902149 ..., 0.27870309 0.27606536
0.27948296]
[ 0.24228902 0.24228902 0.24565263 ..., 0.28212482 0.27948296
0.282906 ]
...,
[ 0.29706944 0.29706944 0.29706944 ..., 0.17470162 0.17144636
0.17144636]
[ 0.29362457 0.29362457 0.29362457 ..., 0.17144636 0.16495056
0.16170998]
[ 0.2901852 0.2901852 0.2901852 ..., 0.16819602 0.16170998
0.15847427]]

Answer

There is numpy's builtin indexing which can be used for replacing elements. This is can be done as:

Image[Image<0.5] = 0