赞
踩
1.先介绍我做的颜色识别的功能,简单的说,就是该脚本可以打开图片,在图片上点击某个区域,可以识别某个区域的颜色,颜色识别准确度很高,很多时候颜色识别是辅助物体的颜色识别,但这个代码你们可以随意修改,就比如你们使用深度学习识别了车子,然后让自动让鼠标点击车子,识别车子颜色,诸如此类。
2.读入图片,使用opencv-python库,安装opencv-python命令
pip install opencv-python
没有设置下载源的使用命令
pip install opencv-python -i https://pypi.tuna.tsinghua.edu.cn/simple
3.我使用的素材颜色图片,因为为了醒目,我选择了颜色鲜明的图,该图如下
4.读取csv文件,使用pandas库,安装pandas库命令
pip install pandas
没有设置下载源的使用命令
pip install pandas -i https://pypi.tuna.tsinghua.edu.cn/simple
5.读取颜色csv表格 ,该表格包含865种颜色判断,每个识别的颜色都会从中进行对比判别,该cvs表格将由我给你们网盘获取,如下
链接:https://pan.baidu.com/s/1LnyDYqcli–aVa2v8zIT-g
提取码:kt05
链接失效了,更新一下:
链接:https://pan.baidu.com/s/1G8JzWWws24HQiLhDxmDn7Q
提取码:yxfj
6.创建一个定义函数draw,该函数是放大颜色区域,在图片上方识别颜色
def draw(event, x, y, flags, parm):
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)
7.创建另一个定义函数getColorName,该函数是将color.csv文件中对比出的颜色名写出
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
8.完整代码呈现
import cv2
import pandas as pd
img_path = "2.png"
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.csv', names=index, header=None)
def draw(event, x, y, flags, parm):
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)
cv2.namedWindow('image')
cv2.setMouseCallback('image', draw) # 鼠标事件响应
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
if __name__ == '__main__':
while (1):
cv2.imshow('image', img)
if (clicked):
cv2.rectangle(img, (20, 20), (750, 60), (b, g, r), -1)
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)
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
9.运行后展示
运行成功的兄弟们希望一键三连,
雄起!!!
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。