I must transform all elements of an ndarray (a grayscale image). In particular if I have the value 0 the desired value is 0 and the values > 0 become 1. Is there a function of numpy that do this? I can do this by two for but I think that it isn't the best solution.
Asked
Active
Viewed 135 times
-1
-
like this? `myarr[myarr > 0] = 1` – Nullman Jul 22 '19 at 10:28
-
like this myarr[myarr>0] = 1 – Giuseppe Puglisi Jul 22 '19 at 10:28
2 Answers
1
You should look up fancy indexing and/or boolean indexing in numpy. Effectively what you can do is as such
array[array>0] = 1
This will set all indices > 0 to 1

Imtinan Azhar
- 1,725
- 10
- 26
1
if you don't want to work "in-place" you can do:
def to_bw(img, dtype=np.uint8):
return (img > 0).astype(dtype)
e.g. you use this as:
import numpy as np
to_bw(np.array([0,1,2]))
it will evaluate to:
array([0, 1, 1])
note this sounds pretty similar to: Convert RGB to black OR white

Sam Mason
- 15,216
- 1
- 41
- 60