jiwopene
jiwopene

Reputation: 3627

Count tuples in array that are equal to same value

I have a NumPy array of shape (100,100,3) (an RGB image). I want to compare all 3-eleemnt tuples contained in the array for equality to produce array of booleans of shape (100,100).

Expected usage:

import numpy as np

arr = np.array([
    [(1,2,3), (2,2,2), (1,2,3), ... ],
    [(0,2,3), (2,2,2), (1,2,3), ... ],
    ...
])
bools = np.some_operation(arr, (1,2,3)
print(bools)
assert(bools == np.array([
    [True,  False, True, ...],
    [False, False, True, ...],
    ...
])

I would like to avoid iterating over the whole array in Python code, since scalar access is not very fast in NumPy.

Upvotes: 1

Views: 76

Answers (1)

OM222O
OM222O

Reputation: 1006

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

target = (1,2,3)

result = np.all(arr==target,axis=2)
print(result)

am I missing something?

Upvotes: 4

Related Questions