赞
踩
https://data-flair.training/blogs/project-in-python-colour-detection/
想做颜色识别,于是找到了一个这样的教程。
发觉对于颜色的精确识别很困难,本文的方法是,找到鼠标敲击处的图片RGB值,在一定容差范围内与已知颜色表进行匹配,从而得到颜色名。
# -*- coding: utf-8 -*- import argparse import cv2 import numpy as np import pandas as pd """directly give an image path from the command prompt""" 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) """declaring global variables (are used later on)""" clicked = False r = g = b = xpos = ypos = 0 """reading csv file with pandas and giving names to each column""" index = ['color','color_name','hex','R','G','B'] csv = pd.read_csv('colors.csv', names=index, header=None) def draw_function(event, x, y, flags, parm): if event == cv2.EVENT_LBUTTONDBLCLK: #鼠标左击 global b, g, r, xpos, ypos, clicked # global parameters, should be in the same file 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"])) if (d <= minimum): minimum = d cname = csv.loc[i, 'color_name'] return cname """set a mouse callback event on a window""" cv2.namedWindow('image') cv2.setMouseCallback('image', draw_function) #鼠标事件响应 """display image on the window""" while(1): cv2.imshow('image', img) if (clicked): cv2.rectangle(img, (20, 20), (750, 60), (b,g,r), -1) """creating text string to display (color name and RGB valuse)""" text = getColorName(r, g, b) + "R=" + str(r) + "G=" + str(g) + "B=" + str(b) 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 color""" if (r+g+b>=600): cv2.putText(img, text, (50,50), 2, 0.8, (0,0,0), cv2.LINE_AA) clicked = False if cv2.waitKey(20) & 0xFF == 27: break cv2.destroyWindow()
argparse.ArgumentParser() 用于添加参数
pandas 读取csv文件很方便
cv2一些函数:
cv2.rectangle(img, (bbox.left, bbox.top), (bbox.right, bbox.bottom), (0,0,255), 2)
靠确定对角线来画矩形。
各参数依次是:图片,左上角坐标,右下角坐标,填充颜色,线粗细(-1则为填充)
cv2.putText(img, str(i), (123,456)), font, 2, (0,255,0), 3)
各参数依次是:图片,添加的文字,左上角坐标,字体,字体大小,颜色,字体粗细
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。