Home > Software design >  How get unique pixels from 2d numpy array?
How get unique pixels from 2d numpy array?

Time:10-19

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.

CodePudding user response:

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]]

CodePudding user response:

How about this?

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