Search code examples
pythonimagenumpyopencv

List of all colors in an image using opencv and python


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


Solution

  • 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.