Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
303 views
in Technique[技术] by (71.8m points)

python - numpy: unique list of colors in the image

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...