Home > Software engineering >  Numpy find position in 3d array based on condition
Numpy find position in 3d array based on condition

Time:10-25

So I have a numpy array representing an opencv image and I want to get all positions where all values of a 1d array in the 3d array fulfill a condition like this:

array1 = [[[186 123 231], [184 126 76]], [[224 187 97], [187 145 243]]]
array2 = [150, 180, 250]

the condition should be that the first element of array1 should be greater and the second and third smaller than their corresponding value in array2 to get this output

[[0 0], [0 1], [1 1]

meaning that the first, second, and fourth elements in array1 fulfilled the condition. I know that there is probably no way to express this worse than I just did but I hope someone can still help me.

CodePudding user response:

  1. numpy solution. Create a mask and use np.where
import numpy as np

array1 = np.array([[[186, 123, 231], [184, 126, 76]], [[224, 187, 97], [187, 145, 243]]])
array2 = np.array([150, 180, 250])

mask = (array1[:, :, 0] > array2[0]) & (array1[:, :, 1] < array2[1]) & (array1[:, :, 2] < array2[2])

print(mask)
positions = np.stack(np.where(mask)).T
print(positions)

Results:

[[0 0]
 [0 1]
 [1 1]]
  1. Also you may consider cv2.inRange:
import numpy as np
import cv2

array1 = np.array([[[186, 123, 231], [184, 126, 76]], [[224, 187, 97], [187, 145, 243]]])
array2 = np.array([150, 180, 250])

# fill lower/upper bounds with artificial 0, 255 values
mask = cv2.inRange(array1, (150, 0, 0), (255, 180, 250))
positions = np.stack(np.where(mask)).T
print(positions)
  • Related