opencv Python 图片颜色识别

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)

各参数依次是:图片,添加的文字,左上角坐标,字体,字体大小,颜色,字体粗细

  • 2
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值