0

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.

2
  • Why do the fourth element in array1 fulfills the condition? The first value should be greater but 87 < 150 Commented Oct 24, 2022 at 18:41
  • Oh yeah, it shouldn't be but I just mistyped there should be 187, not 87 thanks. Commented Oct 24, 2022 at 19:31

1 Answer 1

1
  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)
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.