• For any query, contact us at
  • +91-9872993883
  • +91-8283824812
  • info@ris-ai.com

Color Detection In Images Using Pandas And OpenCV

Project Objective: We will create a basic application that will help us to detect the colors in an image. The program will also return as the RGB values of the colors, which is really helpful. Many graphic designers and web designers will understand how RGB values can be helpful. Building a color recognizer is a great project to get started with Computer Vision.

Importing the libraries

We will use three main modules for this project. They are NumPy, Pandas and OpenCv. OpenCv is a highly optimized library with a focus on real-time applications.

In [1]:
import numpy as np
import pandas as pd
import cv2

Color Identification in images

You can choose any image you want. I will save my image in the same folder as my program, which makes it easier to find and import. Below is the color.jpeg image.

In [2]:
img = cv2.imread('color.jpeg')
Color Detection in Python

We Read The CSV File With Pandas

The pandas library is very useful when we need to perform various operations on data files like CSV. pd.read_csv() reads the CSV file and loads it into the pandas DataFrame. We have assigned each column with a name for easy accessing. We will use the RGB format as our data points. I found a ready csv file with around 1000 color names and the RGB values.We will use this csv file in our program. The screenshot of the file to give you some idea.

In [3]:
index=['color', 'color_name', 'hex', 'R', 'G', 'B']
csv = pd.read_csv('colors.csv', names=index, header=None)

Global Variables

In the following steps, we will define two functions. To make the application work smoothly, we need some global variables. You will know how global variables can be helpful when working with functions.

In [4]:
clicked = False
r = g = b = xpos = ypos = 0

Color Recognition Function

This function will be called when we double click on an area of the image. It will return the color name and the RGB values of that color. This is where the magic happens!

In [5]:
def recognize_color(R,G,B):
    minimum = 10000
    for i in range(len(csv)):
        d = abs(R- int(csv.loc[i,"R"])) + abs(G- int(csv.loc[i,"G"]))+ abs(B- int(csv.loc[i,"B"]))
        if(d<=minimum):
            minimum = d
            cname = csv.loc[i,"color_name"]
    return cname

Mouse Click Function

This function is used to define our double click process. We will need it when creating our application part.

In [6]:
def mouse_click(event, x, y, flags, param):
    if event == cv2.EVENT_LBUTTONDBLCLK:
        global b,g,r,xpos,ypos, clicked
        clicked = True
        xpos = x
        ypos = y
        b,g,r = img[y,x]
        b = int(b)
        g = int(g)
        r = int(r)
Application

I am glad you made it to this step. In this step, we will open the image as a new window using OpenCV methods. And in that window, we will use the functions we defined earlier. The application is so simple, it returns the color name and color values when you double click on a certain area on the image.

Application Window

First things first, let me show you how to open the image file as a new window using OpenCV.

In [7]:
cv2.namedWindow('Color Recognition App')

Secondly, let’s call the mouse click function that we created. This gives more functionality to our application.

In [8]:
cv2.setMouseCallback('Color Recognition App', mouse_click)
The Application

Here is the while loop to start our application window working.

In [9]:
while(1):
    cv2.imshow("Color Recognition App",img)
    if (clicked):
         #cv2.rectangle(image, startpoint, endpoint, color, thickness)-1 fills entire rectangle 
        cv2.rectangle(img,(20,20), (750,60), (b,g,r), -1)
        #Creating text string to display( Color name and RGB values )
        text = recognize_color(r,g,b) + ' R='+ str(r) +  ' G='+ str(g) +  ' B='+ str(b)
        #cv2.putText(img,text,start,font(0-7),fontScale,color,thickness,lineType )
        cv2.putText(img, text,(50,50),2,0.8,(255,255,255),2,cv2.LINE_AA)
        #For very light colours we will display text in black colour
        if(r+g+b>=600):
            cv2.putText(img, text,(50,50),2,0.8,(0,0,0),2,cv2.LINE_AA)
        clicked=False
    
    #Break the loop when user hits 'esc' key    
    if cv2.waitKey(20) & 0xFF ==27:
        break

Double click on the window to know the name of the pixel color

Whenever a double click event occurs, it will update the color name and RGB values on the window. Using the cv2.imshow() function, we draw the image on the window. When the user double clicks the window, we draw a rectangle and get the color name to draw text on the window using cv2.rectangle and cv2.putText() functions. In image you can see the name of selected color and index value of color.

Color Detection in Python

Color Detection in Python
Close the Application

If you worked with OpenCV projects, you may be familiar with this step. We have to define how to end and close the application window. Otherwise, it will run forever since we used while(1) to start the application.

In [10]:
cv2.destroyAllWindows()

Conclusion:

In this Python project with source code, we learned about colors and how we can extract color RGB values and the color name of a pixel. We learned how to handle events like double-clicking on the window and saw how to read CSV files with pandas and perform operations on data. This is used in numerous image editing and drawing apps.