Yaron Scherf
Yaron Scherf

Reputation: 105

Numpy replace values

I got an rgb image (h and w are not constant) and I want to paint green all the pixels that are within certain range (rgb range). I got most of the code working, the thing i struggle with: assume I got the following image:

arr = np.zeros((4,4,3))
arr[0,0] = [2,3,4]
arr[1, 1] = [1, 2, 3]

lets assume the condition is all the pixels that meet the following rule:

t = np.all((arr >= [1,2,3])&(arr <= [1,4,4]),axis = 2)
print(t)
[[False False False False]
[False  True False False]
[False False False False]
[False False False False]]

each value in t represents a pixel in arr, if it's true i want to change the corresponding pixel in arr to be [10,10,10]. meaning i want the output to be:

[[[2. 3. 4.]
  [0. 0. 0.]
  [0. 0. 0.]
  [0. 0. 0.]]

 [[0. 0. 0.]
  [10. 10. 10.]
  [0. 0. 0.]
  [0. 0. 0.]]

 [[0. 0. 0.]
  [0. 0. 0.]
  [0. 0. 0.]
  [0. 0. 0.]]

 [[0. 0. 0.]
  [0. 0. 0.]
  [0. 0. 0.]
  [0. 0. 0.]]]

Im asking for a numpy-ish way to do this.

Upvotes: 0

Views: 76

Answers (1)

Stef
Stef

Reputation: 30579

IIUC you want to do:

arr[t] = [10,10,10]

Example:

>>> arr = np.zeros((4,4,3))
>>> arr[0,0] = [2,3,4]
>>> arr[1,1] = [1,2,3]
>>> t = np.all((arr >= [1,2,3])&(arr <= [1,4,4]),axis = 2)
>>> arr[t] = [10,10,10]
>>> arr
array([[[ 2.,  3.,  4.],
        [ 0.,  0.,  0.],
        [ 0.,  0.,  0.],
        [ 0.,  0.,  0.]],

       [[ 0.,  0.,  0.],
        [10., 10., 10.],
        [ 0.,  0.,  0.],
        [ 0.,  0.,  0.]],

       [[ 0.,  0.,  0.],
        [ 0.,  0.,  0.],
        [ 0.,  0.,  0.],
        [ 0.,  0.,  0.]],

       [[ 0.,  0.,  0.],
        [ 0.,  0.,  0.],
        [ 0.,  0.,  0.],
        [ 0.,  0.,  0.]]])

Upvotes: 1

Related Questions