Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

numpy: unique list of colors in the image

Tags:

python

numpy

I have an image img:

>>> img.shape
(200, 200, 3)

On pixel (100, 100) I have a nice color:

>>> img[100,100]
array([ 0.90980393,  0.27450982,  0.27450982], dtype=float32)

Now my question is: How many different colors are there in this image, and how do I enumerate them?

My first idea was numpy.unique(), but somehow I am using this wrong.

like image 749
wal-o-mat Avatar asked Jul 16 '14 12:07

wal-o-mat


2 Answers

Your initial idea to use numpy.unique() actually can do the job perfectly with the best performance:

numpy.unique(img.reshape(-1, img.shape[2]), axis=0)

At first, we flatten rows and columns of matrix. Now the matrix has as much rows as there're pixels in the image. Columns are color components of each pixels.

Then we count unique rows of flattened matrix.

like image 173
Maksym Ganenko Avatar answered Sep 19 '22 15:09

Maksym Ganenko


You could do this:

set( tuple(v) for m2d in img for v in m2d )
like image 23
usual me Avatar answered Sep 17 '22 15:09

usual me