-1

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.

SecretAgentMan
  • 2,856
  • 7
  • 21
  • 41
Giuseppe Puglisi
  • 423
  • 2
  • 6
  • 17

2 Answers2

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