Color Detection using Pandas and OpenCV

pip install opencv-python numpy pandas
  • — main source code of our project.
  • Color.jpg — sample image for experimenting.
  • Colors.csv — a file that contains our dataset.
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)
#Reading csv file with pandas and giving names to each column
csv = pd.read_csv('colors.csv', names=index, header=None)
def draw_function(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)
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"]))
minimum = d
cname = csv.loc[i,"color_name"]
return cname
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
cv2.putText(img, text,(50,50),2,0.8,(0,0,0),2,cv2.LINE_AA)


#Break the loop when user hits 'esc' key
if cv2.waitKey(20) & 0xFF ==27:

Output Image




Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Dual Path Scripts Interactive and Automated

Easy ETL with Python: a step by step tutorial

Agility & Project Management at Fixed-Cost

A step-by-step guide to finding a code mentor

Try out the try method

Output: Piezo Speakers

voice controlled home automation

How to Create a Writing Portfolio When You Have Zero Experience

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store


More from Medium

What is Generator in Python

External Sensor using ESP32 with BMP280

Introduction To Strings in Python

Battery capacity estimation using Machine Learning : Part-2