Leo_Makarov
Leo_Makarov

Reputation: 13

How get unique pixels from 2d numpy array?

I have 2d array with rgb pixel data (2 row with 3 pixel in a row).

[[[255, 255, 255],[3, 0, 2],[255, 255, 255]],[[255, 255, 255],[3, 0, 2],[255, 255, 255]]]

How can I get unique pixel? I want to get

[[255, 255, 255], [3, 0, 2]]

I am trying to use np.unique and np.transpose with np.reshape but I wasn't able to get the desired result.

Upvotes: 1

Views: 90

Answers (2)

Lazyer
Lazyer

Reputation: 985

How about this?

import itertools
np.unique(np.array(list(itertools.chain(*arr))), axis=0)
array([[  3,   0,   2],
       [255, 255, 255]])

Upvotes: 0

Guy
Guy

Reputation: 50899

Reshape the array to 2D and then use np.unique with axis=0

arr = np.array([[[255, 255, 255],[3, 0, 2],[255, 255, 255]],[[255, 255, 255],[3, 0, 2],[255, 255, 255]]])
shape = arr.shape
arr = arr.reshape((shape[0] * shape[1], shape[2]))
print(np.unique(arr, axis=0))

Output

[[  3   0   2]
 [255 255 255]]

Upvotes: 1

Related Questions