我是靠谱客的博主 尊敬发箍,最近开发中收集的这篇文章主要介绍颜色识别OpenCV,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

下面有多种颜色识别方法,可根据需要进行选择

colorList.py(颜色库)

import numpy as np
import collections

def getColorList():
    dict = collections.defaultdict(list)

    # black
    lower_black = np.array([0, 0, 0])
    upper_black = np.array([180, 255, 46])
    color_list_black = []
    color_list_black.append(lower_black)
    color_list_black.append(upper_black)
    dict['black'] = color_list_black

    # gray
    lower_gray = np.array([0, 0, 46])
    upper_gray = np.array([180, 43, 220])
    color_list_gray= []
    color_list_gray.append(lower_gray)
    color_list_gray.append(upper_gray)
    dict['gray'] = color_list_gray

    # white
    lower_white = np.array([0, 0, 221])
    upper_white = np.array([180, 30, 255])
    color_list_white = []
    color_list_white.append(lower_white)
    color_list_white.append(upper_white)
    dict['white'] = color_list_white

    # red
    lower_red = np.array([156, 43, 46])
    upper_red = np.array([180, 255, 255])
    color_list_red = []
    color_list_red.append(lower_red)
    color_list_red.append(upper_red)
    dict['red'] = color_list_red

    # red2
    lower_red = np.array([0, 43, 46])
    upper_red = np.array([10, 255, 255])
    color_list_red2 = []
    color_list_red2.append(lower_red)
    color_list_red2.append(upper_red)
    dict['red2'] = color_list_red2

    # orange
    lower_orange = np.array([11, 43, 46])
    upper_orange = np.array([25, 255, 255])
    color_list_orange = []
    color_list_orange.append(lower_orange)
    color_list_orange.append(upper_orange)
    dict['orange'] = color_list_orange

    # yellow
    lower_yellow = np.array([26, 43, 46])
    upper_yellow = np.array([34, 255, 255])
    color_list_yellow = []
    color_list_yellow.append(lower_yellow)
    color_list_yellow.append(upper_yellow)
    dict['yellow'] = color_list_yellow

    # green
    lower_green = np.array([35, 43, 46])
    upper_green = np.array([77, 255, 255])
    color_list_green = []
    color_list_green.append(lower_green)
    color_list_green.append(upper_green)
    dict['green'] = color_list_green

    # cyan
    lower_cyan = np.array([78, 43, 46])
    upper_cyan = np.array([99, 255, 255])
    color_list_cyan = []
    color_list_cyan.append(lower_cyan)
    color_list_cyan.append(upper_cyan)
    dict['cyan'] = color_list_cyan

    # blue
    lower_blue = np.array([100, 43, 46])
    upper_blue = np.array([124, 255, 255])
    color_list_blue = []
    color_list_blue.append(lower_blue)
    color_list_blue.append(upper_blue)
    dict['blue'] = color_list_blue

    # purple
    lower_purple = np.array([125, 43, 46])
    upper_purple = np.array([155, 255, 255])
    color_list_purple = []
    color_list_purple.append(lower_purple)
    color_list_purple.append(upper_purple)
    dict['purple'] = color_list_purple

    return dict

if __name__ == '__main__':
    color_dict = getColorList()
    print(color_dict)

    num = len(color_dict)
    print('num=', num)

    for d in color_dict:
        print('key=', d)
        print('value=', color_dict[d][1])

xf_color.py(识别图片面积最大颜色)

import cv2
import colorList

def get_color(frame):
    print('go in get_color')
    hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
    maxsum = 0
    color = None
    color_dict = colorList.getColorList()
    for d in color_dict:
        mask = cv2.inRange(hsv, color_dict[d][0], color_dict[d][1])
        binary = cv2.threshold(mask, 127, 255, cv2.THRESH_BINARY)[1]
        binary = cv2.dilate(binary, None, iterations=2)
        cnts = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[-2]
        sum = 0
        for c in cnts:
            sum += cv2.contourArea(c)
        # print("%s  , %d" %(d, sum ))
        if sum > maxsum:
            maxsum = sum
            color = d
    return color

if __name__ == '__main__':
    filename = "/home/pi/color/yellow.jpg"
    frame = cv2.imread(filename)
    print(get_color(frame))

xf_realize.py(识别摄像头面积最大颜色)

import cv2
import xf_color

def videox():
    vix = cv2.VideoCapture(0)
    while True:
        ret, tu = vix.read()
        cv2.imshow("take_photo", tu)
        cv2.waitKey(1)
        cv2.imwrite("color.png", tu)
        filename = cv2.imread("color.png")
        color = xf_color.get_color(filename)

        if color == "red" or color == "red2":
            print("red")
            result = "1"
            break
        elif color == "green":
            print("green")
            result = "2"
            break
        elif color == "blue":
            print("blue")
            result = "3"
            break
    vix.release()
    cv2.destroyAllWindows()
    return result

if __name__ == '__main__':
    videox()

xf_hsv.py(识别颜色并画框)

import numpy as np
import cv2

font = cv2.FONT_HERSHEY_SIMPLEX

lower_green = np.array([35, 43, 46])  # 绿色低阈值
upper_green = np.array([77, 255, 255])  # 绿色高阈值
lower_red = np.array([0, 127, 128])  # 红色低阈值
upper_red = np.array([10, 255, 255])  # 红色高阈值
lower_blue = np.array([100, 43, 46])  # 蓝色低阈值
upper_blue = np.array([124, 255, 255])  # 蓝色高阈值
lower_yellow = np.array([11, 43, 46])  # 黄色低阈值
upper_yellow = np.array([34, 255, 255])  # 黄色高阈值

cap = cv2.VideoCapture(0)#打开USB摄像头
if (cap.isOpened()):  # 视频打开成功
    flag = 1
else:
    flag = 0
num = 0
if (flag):
    while (True):
        ret, frame = cap.read()  # 读取一帧
        if ret == False:  # 读取帧失败
            break
        
        hsv_img = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
        mask_green = cv2.inRange(hsv_img, lower_green, upper_green)  # 根据颜色范围删选
        mask_red = cv2.inRange(hsv_img, lower_red, upper_red)
        mask_blue = cv2.inRange(hsv_img, lower_blue, upper_blue)
        mask_yellow = cv2.inRange(hsv_img, lower_yellow, upper_yellow)
        
        mask_green = cv2.medianBlur(mask_green, 7)  # 中值滤波
        mask_red = cv2.medianBlur(mask_red, 7)
        mask_blue = cv2.medianBlur(mask_blue, 7)
        mask_yellow = cv2.medianBlur(mask_yellow, 7)
        
        mask = cv2.bitwise_or(mask_green, mask_red, mask_blue, mask_yellow) # 检测轮廓
        mask_green, contours, hierarchy = cv2.findContours(mask_green, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
        mask_red, contours2, hierarchy2 = cv2.findContours(mask_red, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
        mask_blue, contours3, hierarchy3 = cv2.findContours(mask_blue, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
        mask_yellow, contours4, hierarchy4 = cv2.findContours(mask_yellow, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
        
        for cnt in contours:
            (x, y, w, h) = cv2.boundingRect(cnt)
            cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
            cv2.putText(frame, "Green", (x, y - 5), font, 0.7, (0, 255, 0), 2)
        
        for cnt2 in contours2:
            (x2, y2, w2, h2) = cv2.boundingRect(cnt2)
            cv2.rectangle(frame, (x2, y2), (x2 + w2, y2 + h2), (0, 0, 255), 2)
            cv2.putText(frame, "Red", (x2, y2 - 5), font, 0.7, (0, 0, 255), 2)
        
        for cnt3 in contours3:
            (x3, y3, w3, h3) = cv2.boundingRect(cnt3)
            cv2.rectangle(frame, (x3, y3), (x3 + w3, y3 + h3), (255, 0, 0), 2)
            cv2.putText(frame, "Blue", (x3, y3 - 5), font, 0.7, (255, 0, 0), 2)
            
        for cnt4 in contours4:
            (x4, y4, w4, h4) = cv2.boundingRect(cnt4)
            cv2.rectangle(frame, (x4, y4), (x4 + w4, y4 + h4), (0, 255, 255), 2)
            cv2.putText(frame, "Yellow", (x4, y4 - 5), font, 0.7, (0, 255, 255), 2)
        
        num = num + 1
        cv2.imshow("dection", frame)
        cv2.imwrite("imgs/%d.jpg"%num, frame)
        if cv2.waitKey(20) & 0xFF == 27:
            break
cv2.waitKey(0)
cv2.destroyAllWindows()

gaussian.py(利用高斯等操作进行处理后的颜色识别)

import cv2
import numpy as np

color_dist = {'red': {'Lower': np.array([0, 127, 128]), 'Upper': np.array([10, 255, 255])},
              'light_red': {'Lower': np.array([178, 100, 136]), 'Upper': np.array([255, 255, 255])},
              'blue': {'Lower': np.array([100, 80, 46]), 'Upper': np.array([124, 255, 255])},
              'green': {'Lower': np.array([35, 43, 35]), 'Upper': np.array([90, 255, 255])},
              'yellow': {'Lower': np.array([26, 43, 46]), 'Upper': np.array([34, 255, 255])},
              }

cap = cv2.VideoCapture(0) 
cv2.namedWindow('camera', cv2.WINDOW_AUTOSIZE)

while True:
    ret, frame = cap.read()
    gs_frame = cv2.GaussianBlur(frame, (5, 5), 0) # 高斯
    hsv = cv2.cvtColor(gs_frame, cv2.COLOR_BGR2HSV) # HSV
    inRange_hsv = cv2.inRange(hsv, color_dist['green']['Lower'], color_dist['green']['Upper']) # 二值化
    cnts = cv2.findContours(inRange_hsv.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[-2] # 检测轮廓
    c = max(cnts, key=cv2.contourArea)
    rect = cv2.minAreaRect(c) # 最小外接矩形
    box = cv2.boxPoints(rect) # 获取顶点坐标
    box_list = box.tolist()

    cv2.drawContours(frame, [np.int0(box)], -1, (0, 255, 0), 2)

    cv2.imshow('camera', frame)
    if cv2.waitKey(1) & 0xFF == 27:
        break
            
cv2.destroyAllWindows()

下面是HSV表与BGR表可根据需要修改自己的数据

HSV

HSV表

BGR

BGR表

最后

以上就是尊敬发箍为你收集整理的颜色识别OpenCV的全部内容,希望文章能够帮你解决颜色识别OpenCV所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(55)

评论列表共有 0 条评论

立即
投稿
返回
顶部