[Small case: 2] OpenCV color tracking

1. Function API

It has been mentioned in the previous articles, so I won’t introduce too much:
OpenCV Quick Start 4: TrackBar Control (Slider)
OpenCV Quick Start 5: Color Space Conversion

Two: Code demonstration

Threshold size determination:

import cv2
import numpy as np

def mcallback(x):
    pass

cv2.namedWindow("Tracking")
#绿色的HSV:可能不是很准
#l_g = np.array([35, 43, 46]) # 下限
#u_g = np.array([77,255,255]) # 上限
cv2.createTrackbar("LH", "Tracking", 0, 255, mcallback)
cv2.createTrackbar("LS", "Tracking", 0, 255, mcallback)
cv2.createTrackbar("LV", "Tracking", 147, 255, mcallback)
cv2.createTrackbar("UH", "Tracking", 100, 255, mcallback)
cv2.createTrackbar("US", "Tracking", 45, 255, mcallback)
cv2.createTrackbar("UV", "Tracking", 255, 255, mcallback)


cap = cv2.VideoCapture(0)
while True:
    ret, frame = cap.read()
    # img = cv2.imread(r"C:\Users\DMr\Pictures\text\book.jpg")
    hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)

    l_h = cv2.getTrackbarPos("LH", "Tracking")
    l_s = cv2.getTrackbarPos("LS", "Tracking")
    l_v = cv2.getTrackbarPos("LV", "Tracking")

    u_h = cv2.getTrackbarPos("UH", "Tracking")
    u_s = cv2.getTrackbarPos("US", "Tracking")
    u_v = cv2.getTrackbarPos("UV", "Tracking")

    l_g = np.array([l_h, l_s, l_v])  
    u_g = np.array([u_h, u_s, u_v])

    mask = cv2.inRange(hsv, l_g, u_g)

    res = cv2.bitwise_and(frame, frame, mask=mask)  

    cv2.imshow("img", frame)
    cv2.imshow("mask", mask)
    cv2.imshow("res", res)
    key = cv2.waitKey(10)
    if(key & 0xff == ord('q')):
        break

cv2.destroyAllWindows()


Color Tracking:

import numpy as np
import cv2

font = cv2.FONT_HERSHEY_SIMPLEX

lower_green = np.array([40, 56, 108])  # 绿色低阈值
upper_green = np.array([85, 156, 235])  # 绿色高阈值
lower_red = np.array([7, 132, 154])  # ju色低阈值
upper_red = np.array([17, 226, 245])  # ju色高阈值
lower_blue = np.array([85, 68, 71])  # 蓝色低阈值
upper_blue = np.array([141, 186, 255])  # 蓝色高阈值
lower_yellow = np.array([12, 59, 168])  # 黄色低阈值
upper_yellow = np.array([35, 141, 255])  # 黄色高阈值
lower_white = np.array([75, 0, 158])  # bai色低阈值
upper_white = np.array([118, 64, 247])  # 白色高阈值

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_white = cv2.inRange(hsv_img, lower_white, upper_white)

        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_white = cv2.medianBlur(mask_white, 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)
        contours = sorted(contours, key=cv2.contourArea, reverse=True)[:2] # 取面积最大的2个
        mask_red, contours2, hierarchy2 = cv2.findContours(mask_red, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
        contours2= sorted(contours2, key=cv2.contourArea, reverse=True)[:1]
        mask_blue, contours3, hierarchy3 = cv2.findContours(mask_blue, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
        contours3 = sorted(contours3, key=cv2.contourArea, reverse=True)[:2]
        mask_yellow, contours4, hierarchy4 = cv2.findContours(mask_yellow, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
        #contours4 = sorted(contours4, key=cv2.contourArea, reverse=True)[:1]
        mask_white, contours5, hierarchy5 = cv2.findContours(mask_white, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
        contours5 = sorted(contours5, key=cv2.contourArea, reverse=True)[:1]

        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, 115, 255), 2)
            cv2.putText(frame, "Orange", (x2, y2 - 5), font, 0.7, (0, 115, 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)

        for cnt5 in contours5:
            (x5, y5, w5, h5) = cv2.boundingRect(cnt5)
            cv2.rectangle(frame, (x5, y5), (x5 + w5, y5 + h5), (255, 255, 255), 2)
            cv2.putText(frame, "White", (x5, y5 - 5), font, 0.7, (255, 255, 255), 2)


        cv2.imshow("color_det", frame)

        if cv2.waitKey(20) & 0xFF == ord("q"):
            break
cv2.waitKey(0)
cv2.destroyAllWindows()

The effect is as follows
color detection

Daily "big pie"
as long as you want to win, no one can make you lose

Guess you like

Origin blog.csdn.net/weixin_52051554/article/details/126890667