How can I pick specific ranged value from np array?

Viewed 36

My code is this.

a = cv2.imread('img_directory',0)/255
a0 = np.zeros_like(a)
a0[a<0.9] = 1.0
a0[a>0.5] = 0.0

Here, I want to take values of a that is larger than 0.5, and smaller than 0.9. But I see that this code does not work properly. First I tried

a=[a<0.9 and a>0.5] =1.0

and this did not work. How should I make a code to fulfill my task ?

2 Answers

If you want to logical and of two numpy array, use np.logical_and(), you can refer to document for more information.

Therefore, a=[np.logical_and((a<0.9), (a>0.5))] = 1.0 will work.

If you just want to select values in a certain range, you can use a mask like this:

from cv2 import cv2
import numpy as np

a = cv2.imread('image_path',0)/255
mask = np.logical_and(0.5 < a, a < 0.9)

# you could then set these values to something else for example, like:
a[mask] = 0.75
Related