Computer Vision / case study
Dominant Color Extraction with K-Means
A computer vision project that clusters every pixel of an image with K-Means, ranks the resulting colours by how much of the image they cover, and draws them as a proportional palette.
- Python
- OpenCV
- scikit-learn
- NumPy
- Matplotlib
- 45.01%
- of the image covered by its single dominant colour
- K-Means, 5 clusters, random state 42
- 2,666,000
- pixels processed
- every pixel, RGB colour space
- 5
- colour clusters ranked by pixel count
- from #0C1717 to #A80629
Every pixel carries an RGB value. K-Means groups pixels with similar colour characteristics, the cluster centroids become the dominant colours, and the number of pixels assigned to each centroid decides its prominence.
The output reports each colour as RGB, HEX, pixel count and percentage, then renders the palette with Matplotlib so the numbers can be checked against the image.

Algorithm
- Load the image with OpenCV and convert it from BGR to RGB.
- Reshape the image into a two-dimensional array of RGB pixel values.
- Apply K-Means clustering with a predefined number of clusters.
- Extract cluster centroids as representative colours and count pixel assignments.
- Rank clusters by pixel frequency and visualize the palette with Matplotlib.
Sample result
Five clusters on a 2,666,000 pixel image.
| Rank | RGB | HEX | Pixels | Share |
|---|---|---|---|---|
| 1 | 12, 23, 23 | #0C1717 | 1,200,085 | 45.01% |
| 2 | 99, 104, 15 | #63680F | 490,126 | 18.38% |
| 3 | 183, 181, 61 | #B7B53D | 390,118 | 14.63% |
| 4 | 6, 105, 150 | #066996 | 388,944 | 14.59% |
| 5 | 168, 6, 41 | #A80629 | 196,727 | 7.38% |
Implementation
Three entry points: Color_extraction.py for the main K-Means workflow, Extraction.py as a consolidated implementation, and Extraction_GUI.py for an experimental Tkinter interface with image selection.
Limitations
- RGB Euclidean distance does not perfectly represent human colour perception.
- Processing every pixel is expensive on high-resolution images.
- The number of clusters has to be chosen in advance.
- The main implementation reads a locally configured image path.