numpy array - more and less than

14.2k Views Asked by At

i have a numpy array:(for example:)

>>> pixels
array([[233, 233, 233],
       [245, 245, 245],
       [251, 251, 251],
       [248, 248, 248],
       [248, 248, 248],
       [248, 248, 248],
       [248, 248, 248],
       [248, 248, 248],
       [248, 248, 248],
       [248, 248, 248]], dtype=uint8)

what can i do to get a boolean array for the values that great than 230 and lower than 240 (for example)? when i write

230<pixels<240

i get this massage:

Traceback (most recent call last):
  File "<pyshell#78>", line 1, in <module>
    100<pixels<300
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

it is also does not work if i write

230<pixels and 240>pixels

thanks a lot!

1

There are 1 best solutions below

0
On

With numpy.where routine:

import numpy as np
a = np.array([[233, 233, 233],
       [245, 245, 245],
       [251, 251, 251],
       [248, 248, 248],
       [248, 248, 248],
       [248, 248, 248],
       [248, 248, 248],
       [248, 248, 248],
       [248, 248, 248],
       [248, 248, 248]], dtype='uint8')

b = np.where((a > 230) & (a < 240), True, False)
print(b)

The output:

[[ True  True  True]
 [False False False]
 [False False False]
 [False False False]
 [False False False]
 [False False False]
 [False False False]
 [False False False]
 [False False False]
 [False False False]]