How to Find the Dominant Color in an Image Using Python

How to Find the Domainant Color in an Image Using Python

Introduction

Install modules

To install the above modules run the commands below on your terminal.

pip3 install opencv-python

pip3 install numpy

pip3 install scikit-learn

Create a file called app.py which will contain our source code.

Below is the image under the experiment, we will use this image to extract the dominant colors

Import modules

Now let’s import the following modules in our app.py file as shown below.

import cv2
import numpy as np
from sklearn.cluster import KMeans

Create function

Now let’s create a function to extract the colors.

def find_dominant_color(image_path, k=3):
    # Load the image
    image = cv2.imread(image_path)
    
    # Convert image from BGR to RGB format
    image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
    
    # Reshape the image to a flattened array of pixels
    pixels = image_rgb.reshape(-1, 3)
    
    # Perform k-means clustering to find dominant colors
    kmeans = KMeans(n_clusters=k)
    kmeans.fit(pixels)
    
    # Get the RGB values of the dominant colors
    colors = kmeans.cluster_centers_
    
    # Convert the colors to integer values
    dominant_colors = colors.astype(int)
    
    return dominant_colors

Now let’s call our function.

image_path = 'valley.jpg'
dominant_colors = find_dominant_color(image_path)
print(dominant_colors)

Results

Here are the dominant RGB values in the image.

[198 140 142]
[102 66 49]
[ 62 86 123]]

There you have it, thanks for reading. Happy Coding

Leave a Comment

Your email address will not be published. Required fields are marked *