2

I have a numpy 3 d array full of RGB values like for exemple shape = (height,width,3)

  matrix = np.array( [[[0,0.5,0.6],[0.9,1.2,0]])

I have to replace the RGB value if any of the values is above a threshold, for exemple threshold = 0.8, replacement = [2,2,2] then

matrix = [[[0,0.5,0.6],[2,2,2]]

How can I do this on a efficient mannner with numpy ? Currently I am using a double for loop and checking if any rgb value is above treshold, i replace it however this is quiet slow for n = 4000 array.

How would I do this more efficient with numpy, maybe something with np.where ?

swaffelay
  • 323
  • 2
  • 10

1 Answers1

2

I've expanded your matrix by another width dimension.

matrix = np.array([[[0,0.5,0.6],[0.9,1.2,0]],[[0,0.5,0.6],[0.9,1.2,0]]])

You can build a mask by using np.any on axis 2 (starts with 0, so third axis):

mask = np.any((matrix > 0.8), axis=2)

# mask:
array([[False,  True],
       [False,  True]], dtype=bool)

matrix[mask] = np.array([2,2,2])

Your resulting matrix:

array([[[ 0. ,  0.5,  0.6],
        [ 2. ,  2. ,  2. ]],

       [[ 0. ,  0.5,  0.6],
        [ 2. ,  2. ,  2. ]]])
Rocky Li
  • 5,641
  • 2
  • 17
  • 33