Reputation: 325
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
Upvotes: 7
Views: 13337
Reputation: 1356
I tried to add this as a comment but realised that it was unreadable. I henceforth add this as an answer but all upvotes can go to iRoNic's post. Here 'cropped' is the image we are interested in and we want to extract prominent colors (instead of all colors) which is usually the use-case:
all_rgb_codes = cropped.reshape(-1, cropped.shape[-1])
unique_rgbs = np.unique(all_rgb_codes, axis=0, return_counts=True)
prominent_2_colors = np.argsort(unique_rgbs[1])[-2:]
foreground_idx, background_idx = prominent_2_colors[-2], prominent_2_colors[-1]
foreground_color, background_color = unique_rgbs[0][foreground_idx], unique_rgbs[0][background_idx]
print('foreground color:', foreground_color, 'background color:', background_color)
Here I am extracting the prominent 2 colors but similar logic can be extended further to get more colors
Upvotes: 0
Reputation: 340
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.
Upvotes: 13