6
votes

Python beginner here. I'm using python 3.6 and opencv and I'm trying to create a list of rgb values of all colors present in an image. I can read the rgb values of one pixel using cv2.imread followed by image[px,px]. The result is a numpy array. What I want is list of rgb tuples of unique colors present in an image and am not sure how to do that. Any help is appreciated. TIA

1
Have you tried the naive aproach of just looping over the whole image and collecting every unique color (i.e. keep a list/dict/whatever with every color seen so far) - FlyingTeller
I wasn't sure how to convert from array to tuple and I just searched and apparantly tuple(a) where a is array gives tuple lol (forgive me, I just started learning python). So, I'm trying the looping approach now. Meanwhile, it'd be great if someone could share a better approach since I have to loop it over 3000 images and it may take a long time. - Kalyan M

1 Answers

10
votes

Check out numpy's numpy.unique() function:

import numpy as np

test = np.array([[255,233,200], [23,66,122], [0,0,123], [233,200,255], [23,66,122]])
print(np.unique(test, axis=0, return_counts = True))

>>> (array([[  0,   0, 123],
       [ 23,  66, 122],
       [233, 200, 255],
       [255, 233, 200]]), array([1, 2, 1, 1]))

You can collect the RGB numpy arrays in a 2D numpy array and then use the numpy.unique() funtion with the axis=0 parameter to traverse the arrays within. Optional parameter return_counts=True will also give you the number of occurences.