Python Color Detection script with OpenCV

Python Color Detection script with OpenCV

Python Color Detection using OpenCV & Python.

Follow the below steps on how to detect and track a color using Python and OpenCV.

What is Color Detection?

The process works using a computer application that color name form an image and color detection is the process of detecting the name of any color.

Python Color Detection script with OpenCV

Installation Steps:

Step 1:

pip install opencv-python numpy pandas argparse

Step 2:

Here we can give an image path from the command prompt.

import cv2
import numpy as np
import pandas as pd
import argparse

ap = argparse.ArgumentParser()
ap.add_argument('-i', '--image', required=True, help="Image Path")
args = vars(ap.parse_args())
img_path = args['image']

#Reading image with opencv
img = cv2.imread(img_path)

clicked = False
r = g = b = xpos = ypos = 0

Step 3:

Read the CSV file using the pandas module and Use a pd.read_csv() method to reads the CSV file.

index=["color","color_name","hex","R","G","B"]
csv = pd.read_csv('colors-database.csv', names=index, header=None)

Step 4:

Set a callback event when the mouse hovers on an image to detect and show the color name.

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

Step 5:

Get the color name method.
def getColorName(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

Step 6:

Set a callback event when the mouse hovers on an image to detect and show the color name.
cv2.namedWindow('image')
cv2.setMouseCallback('image',draw_function)

Step 7:

Showing image on the window and double click on the image, it will show the color name and RGB values on the image window.
while(1):
  cv2.imshow("image",img)
  if (clicked):
    #cv2.rectangle(image, startpoint, endpoint, color, thickness) -1 thickness fills rectangle entirely
    cv2.rectangle(img,(20,20), (750,60), (b,g,r), -1)
    #Creating text string to display ( Color name and RGB values )
    text = getColorName(r,g,b) + ' R='+ str(r) + ' G='+ str(g) + ' B='+ str(b)
    #cv2.putText(img,text,start,font(0-7), fontScale, color, thickness, lineType, (optional bottomLeft bool) )
    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
cv2.destroyAllWindows()

Step 8:

Run python file in terminal using command line script as below.
python detect_color_from_image.py -i <ADD_YOUR_IMAGE_FILE_PATH_HERE>
Python Color Detection script with OpenCV

Complete code in one shot as below.

import cv2
import numpy as np
import pandas as pd
import argparse

ap = argparse.ArgumentParser()
ap.add_argument('-i', '--image', required=True, help="Image Path")
args = vars(ap.parse_args())
img_path = args['image']

#Reading image with opencv
img = cv2.imread(img_path)

clicked = False
r = g = b = xpos = ypos = 0

index=["color","color_name","hex","R","G","B"]
csv = pd.read_csv('colors-database.csv', names=index, header=None)

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


def getColorName(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

cv2.namedWindow('image')
cv2.setMouseCallback('image',draw_function)


while(1):
  cv2.imshow("image",img)
  if (clicked):
    #cv2.rectangle(image, startpoint, endpoint, color, thickness) -1 thickness fills rectangle entirely
    cv2.rectangle(img,(20,20), (750,60), (b,g,r), -1)
    #Creating text string to display ( Color name and RGB values )
    text = getColorName(r,g,b) + ' R='+ str(r) + ' G='+ str(g) + ' B='+ str(b)
    #cv2.putText(img,text,start,font(0-7), fontScale, color, thickness, lineType, (optional bottomLeft bool) )
    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
cv2.destroyAllWindows()
Any query? Please share your thoughts in the comments below. Glad to help you!
Thanks!
Was this page helpful? Do not forget to share this post!

Leave a Reply

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