Color Detection Project Using Python
By Rohit Sharma
Updated on Jul 28, 2025 | 9 min read | 1.26K+ views
Share:
For working professionals
For fresh graduates
More
By Rohit Sharma
Updated on Jul 28, 2025 | 9 min read | 1.26K+ views
Share:
Table of Contents
Color detection is a fundamental yet powerful application in computer vision. It assists systems in identifying colors from images to further act on them. In this project, we will develop a color detection model with Python and OpenCV. It will show the name and RGB values of any color that is clicked on an image.
This is very useful in real life, far beyond just editing images. In robotics, detecting the color of an object is equally important as recognizing the object itself. In tasks like sorting, navigation, or object tracking, being able to detect color makes a robot more accurate in understanding its surroundings.
Explore more project ideas like this in our Top 25+ Essential Data Science Projects GitHub to Explore in 2025 blog.
Before you start this project, you will want to have at least some basic knowledge of the following:
For this project, the following tools and libraries will be used:
Tool / Library |
Purpose |
Python |
Programming language used for development |
Google Colab |
Online IDE to write and run the code |
NumPy |
For array operations and numerical handling |
OpenCV |
To process images and handle color detection |
Pandas (optional) |
You can complete this project in around 1.5 hours. It serves as a great beginner-level hands-on introduction to OpenCV and basic image processing.
It is advisable that you get some sound understanding of how color detection even works at the basic level before trying for the actual color detection app.
Color detection reads an image and identifies the color of a pixel at a given (x, y) position. The RGB (Red, Green, Blue) values of that pixel will then be compared against a list of color names in a stored CSV file.
The comparison is usually done using a simple mathematical distance formula - the lesser the distance between the RGB values, the better the match! After locating the closest match, the program displays the name of the color on the image itself.
Now that you have a basic understanding of how color detection works, let’s begin building the model step by step. We will start by:
Without any further delay, let’s start!
To build a color detection model, we will use the color detection dataset available on Kaggle. Follow the steps mentioned below to download the dataset:
Now that you have downloaded the file, upload it to Google Colab using the code below:
from google.colab import files
# Upload both the image and the CSV file
uploaded = files.upload()
This will prompt you to choose a file from your system. Select the image and the .csv file you just downloaded.
Once uploaded, use the code given below to load as well as preview the dataset:
import pandas as pd
# Load the CSV dataset
csv_path = 'colors.csv'
colors_df = pd.read_csv(csv_path)
# Show the first five rows
colors_df.head()
Doing so will help you verify that the dataset is loaded correctly.
air_force_blue_raf |
Air Force Blue (Raf) |
#5d8aa8 |
93 |
138 |
168 |
|
0 |
air_force_blue_usaf |
Air Force Blue (Usaf) |
#00308f |
0 |
48 |
143 |
1 |
air_superiority_blue |
Air Superiority Blue |
#72a0c1 |
114 |
160 |
193 |
2 |
alabama_crimson |
Alabama Crimson |
#a32638 |
163 |
38 |
56 |
3 |
alice_blue |
Alice Blue |
#f0f8ff |
240 |
248 |
255 |
4 |
alizarin_crimson |
Alizarin Crimson |
#e32636 |
227 |
38 |
54 |
As we can see, the dataset does not include columns like - color, color_name, hex, R, G, and B. Hence, it does not match the typical structure required for a color detection project in Python using OpenCV. So let’s rename the columns manually.
You can do this by using the below code.
# Rename columns to expected names
colors_df.columns = ['color', 'color_name', 'hex', 'R', 'G', 'B']
Note: Do this only when you don’t have a proper dataset with the columns mentioned above.
Now, let’s see whether the dataset columns have changed or not. We can confirm this by viewing the first 5 rows of the dataset. To do this, use the code below:
# Show the first five rows
colors_df.head()
color |
color_name |
hex |
R |
G |
B |
|
0 |
air_force_blue_usaf |
Air Force Blue (Usaf) |
#00308f |
0 |
48 |
143 |
1 |
air_superiority_blue |
Air Superiority Blue |
#72a0c1 |
114 |
160 |
193 |
2 |
alabama_crimson |
Alabama Crimson |
#a32638 |
163 |
38 |
56 |
3 |
alice_blue |
Alice Blue |
#f0f8ff |
240 |
248 |
255 |
4 |
alizarin_crimson |
Alizarin Crimson |
#e32636 |
227 |
38 |
54
|
Now that the dataset has standard columns, let’s move on to the next step.
In this step, we will load the image on which we will perform color detection. We will use OpenCV (cv2) to read and display the image.
Use the below code:
import cv2
from google.colab.patches import cv2_imshow
# Load the image using OpenCV
img = cv2.imread('colorpic.jpg')
# Resize the image (optional for better fit on screen)
img = cv2.resize(img, (800, 600))
# Display the image
cv2_imshow(img)
Once the code is executed, you will be able to see the image.
Popular Data Science Programs
Note: We usually use cv2.imshow() to display images with OpenCV in a normal local Python environment, like - Jupyter or your desktop. But in Google Colab, cv2.imshow() does not work because Colab runs in a browser-based, non-GUI environment. That’s why we used - cv2_imshow() from google.colab.patches.
To identify the color of any pixel, we need to extract its RGB values. Since Google Colab doesn't support GUI-based interaction like mouse clicks, we will manually provide the x and y coordinates of the pixel we want to analyze.
Here’s the code to accomplish the same:
# Load the image using OpenCV
import cv2
from google.colab.patches import cv2_imshow
img = cv2.imread('colorpic.jpg')
# Display the image
cv2_imshow(img)
# Input coordinates of the pixel you want to detect
x = 100 # change as needed
y = 150 # change as needed
# Get the RGB values at that point
b, g, r = img[y, x]
print(f"RGB at ({x},{y}) - R:{r}, G:{g}, B:{b}")
Output
The above code prints the RGB value of the pixel at the selected (x, y) position (highlighted in red). We will use them to identify and display the closest matching color name on the image in the next step.
Now that we can get the RGB value from any clicked point on the image, in this step we will match the above RGB that we got with the closest color name from our dataset. Since Colab doesn’t support GUI-based mouse interactions, we will manually simulate a pixel click by choosing specific coordinates on the image.
Use the below code to accomplish this:
# Function to get the closest color name
def get_color_name(R, G, B):
minimum = float('inf')
color_name = ""
for i in range(len(colors_df)):
d = abs(R - int(colors_df.loc[i, 'R'])) + abs(G - int(colors_df.loc[i, 'G'])) + abs(B - int(colors_df.loc[i, 'B']))
if d < minimum:
minimum = d
color_name = colors_df.loc[i, 'color_name']
return color_name
# Choose a pixel location manually (simulate a click)
x, y = 100, 150 # Example coordinates
b, g, r = img[y, x]
# Get the color name
detected_color = get_color_name(r, g, b)
# Display the result
print(f"Color at ({x}, {y}) - Name: {detected_color}, R: {r}, G: {g}, B: {b}")
You will get this output:
Output
Color at (100, 150) - Name: Myrtle, R: 82, G: 13, B: 34
/tmp/ipython-input-9-1919190612.py:7: RuntimeWarning: overflow encountered in scalar subtract
d = abs(R - int(colors_df.loc[i, 'R'])) + abs(G - int(colors_df.loc[i, 'G'])) + abs(B - int(colors_df.loc[i, 'B']))
/tmp/ipython-input-9-1919190612.py:7: RuntimeWarning: overflow encountered in scalar add
d = abs(R - int(colors_df.loc[i, 'R'])) + abs(G - int(colors_df.loc[i, 'G'])) + abs(B - int(colors_df.loc[i, 'B']))
Now let's visualize the above result by drawing a filled rectangle and writing the color name along with its RGB values on top of the image. Since we are in Google Colab, we simulate the pixel selection manually (just like Step 5) before drawing.
Here’s the code to do so:
# Example: Simulated pixel coordinates
x, y = 100, 150 # You can change this to any coordinate you want
# Get the RGB values at that point (remember OpenCV reads in BGR format)
B = int(img[y, x][0])
G = int(img[y, x][1])
R = int(img[y, x][2])
# Match the color using your get_color_name function
color_name = get_color_name(R, G, B)
# Make a copy of the original image to draw on
output_img = img.copy()
# Define rectangle position and size
rectangle_start = (20, 20)
rectangle_end = (750, 60)
# Draw the filled rectangle using the detected color
cv2.rectangle(output_img, rectangle_start, rectangle_end, (B, G, R), -1)
# Define the text to display
text = f"{color_name} R={R} G={G} B={B}"
# Choose text color for visibility
text_color = (255, 255, 255) if R + G + B < 600 else (0, 0, 0)
# Put the color name text on the image
cv2.putText(output_img, text, (30, 50), cv2.FONT_HERSHEY_SIMPLEX, 0.8, text_color, 2)
# Show the final image
cv2_imshow(output_img)
You will get output something like this:
Color detection is a strong computer vision concept that allows us to gain meaningful insight from the input data. In this project, we learned how to use Python and OpenCV to detect colors in an image depending on pixel-level RGB values. Nested within our exploration was finding ways to map these values against a predefined color name dataset, while simultaneously highlighting the detected colors on the image.
Though the limitations were many, especially on Google Colab that doesn't support GUI interaction, somehow we resorted to simulating a pixel click and saved the day creating a working model of color detection. This can be extended to a great deal of applications, such as dominant color detection, color filters, or assistive technology for colorblind users.
Unlock the power of data with our popular Data Science courses, designed to make you proficient in analytics, machine learning, and big data!
Elevate your career by learning essential Data Science skills such as statistical modeling, big data processing, predictive analytics, and SQL!
Stay informed and inspired with our popular Data Science articles, offering expert insights, trends, and practical tips for aspiring data professionals!
803 articles published
Rohit Sharma is the Head of Revenue & Programs (International), with over 8 years of experience in business analytics, EdTech, and program management. He holds an M.Tech from IIT Delhi and specializes...
Speak with Data Science Expert
By submitting, I accept the T&C and
Privacy Policy
Start Your Career in Data Science Today
Top Resources