更改cv2.rectangle的颜色

时间:2019-10-03 08:23:25

标签: python opencv colors

我正在尝试创建一种颜色检测系统,当我单击窗口时它会告诉颜色。我现在正在尝试制作cv2.rectangle的颜色,以将颜色更改为我单击的颜色。

这是我到目前为止所做的

import cv2
import webcolors
from tkinter import *
from PIL import Image
from PIL import ImageTk
from tkinter import filedialog
import cv2
# --- functions ---

def closest_colour(requested_colour):
    global colorcode
    colorcode = requested_colour
    min_colours = {}
    for key, name in webcolors.css3_hex_to_names.items():
        r_c, g_c, b_c = webcolors.hex_to_rgb(key)
        rd = (r_c - requested_colour[0]) ** 2
        gd = (g_c - requested_colour[1]) ** 2
        bd = (b_c - requested_colour[2]) ** 2
        min_colours[(rd + gd + bd)] = name
    return min_colours[min(min_colours.keys())]

def get_colour_name(requested_colour):

    try:
        closest_name = actual_name = webcolors.rgb_to_name(requested_colour)
    except ValueError:
        closest_name = closest_colour(requested_colour)
        actual_name = ""
    return actual_name, closest_name

def click_event(event, x, y, flags, param):
    global closest_name, colour2 # inform function to assign to global/external variable instead of creating local one

    if event == cv2.EVENT_LBUTTONDOWN:
        B, G, R = frame[x, y]
        colour2 = (R, G, B)  # reverse values
        colour = frame[y,x][::-1] # reverse values
        actual_name, closest_name = get_colour_name(colour)


font = cv2.FONT_HERSHEY_DUPLEX

closest_name = '' # create global variable at start
requested_colour = ''
cap = cv2.VideoCapture(0);

cv2.namedWindow('frame')
cv2.setMouseCallback('frame', click_event)

while True:
    ret, frame = cap.read()

    if closest_name:
        cv2.rectangle(frame, (600, 60), (0, 0), (224, 224, 224),cv2.FILLED)
        cv2.rectangle(frame, (10, 10), (100, 50), (colour2), -1)
        cv2.rectangle(frame, (10, 10), (100, 50), (0, 0, 0), 2)

        cv2.putText(frame, closest_name, (110, 40), font, 1, (0, 0, 0), 1)


    cv2.imshow('frame', frame)
    cv2.resizeWindow('frame', 500, 450)

    if cv2.waitKey(40) == 27:
        break

这是我遇到的错误

  

跟踪(最近一次通话最近):文件“ C:/ Users / Suhail   Misbah / PycharmProjects / Color_Detection / colordetection.py“,第70行,在          cv2.rectangle(frame,(10,10),(100,50),(colour2),-1)TypeError:需要一个整数(元组类型元组)

1 个答案:

答案 0 :(得分:1)

color的{​​{1}}参数期望一个3整数的元组,代表三个颜色分量RGB。通过以下方式调用该函数:

cv2.rectangle

您将以下元组传递给函数:colour2 = (R,G,B) cv2.rectangle(frame, (10, 10), (100, 50), (colour2), -1) ,这是一个包含一个元素的元组:元组。使用

((R,G,B))

相反。

更新cv2.rectangle(frame, (10, 10), (100, 50), colour2, -1) 返回的颜色分量似乎是frame[x,y]。但是,numpy.uint8的{​​{1}}参数需要一个Python color。您需要先转换颜色分量,例如:

cv2.rectangle