opencv交通灯检测

时间:2021-03-11 20:18:19

标签: python opencv image-processing computer-vision

import cv2 
import numpy as np

import warnings
warnings.filterwarnings("ignore")

cap = cv2.VideoCapture(0)

while True :
    ret ,frame = cap.read()
    
    hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
    
    lower_yellow = np.array([20,0,0])
    upper_yellow = np.array([40,255,255])
    
    mask = cv2.inRange(hsv, lower_yellow, upper_yellow)
    res = cv2.bitwise_and(frame,frame, mask= mask)
    
    img = cv2.medianBlur(res, 5)
    ccimg = cv2.cvtColor(img, cv2.COLOR_HSV2BGR)
    cimg = cv2.cvtColor(ccimg, cv2.COLOR_BGR2GRAY)
    circles = cv2.HoughCircles(cimg, cv2.HOUGH_GRADIENT, 1, 20,param1=50, param2=30, minRadius=20, maxRadius=30)
    if circles is not None:
        print("circle is found")
        circles = np.uint16(np.around(circles))
        for i in circles[0, :]:
                cv2.circle(cimg, (i[0], i[1]), i[2], (0, 255, 0), 2)
                cv2.circle(cimg, (i[0], i[1]), 2, (0, 0, 255), 3)
    cv2.imshow('detected circles', cimg)
    cv2.imshow('res',res)
      
    if cv2.waitKey(1) & 0xFF == ord("q"):
        break
cv2.destroyAllWindows()

我想通过使用 opencv 来检测交通灯,最初我想通过使用 HSV 空间然后中值滤波并找到圆圈来检测黄色,但它会引发错误 async ReadSample() call is failed with error status: -1072873821OnReadSample() is called with error status: -1072873821 可能错误是由检查是否找到任何圆的 if 状态引起的,错误是一个很长的列表,但这两个重复。

1 个答案:

答案 0 :(得分:0)

捕获设备无法读取帧。 OnReadSample() 调用在 cap.read() 上失败,您应该实现逻辑来处理未被读取的帧。我已经在下面演示了这一点:

import cv2
import numpy as np

import warnings

warnings.filterwarnings("ignore")

cap = cv2.VideoCapture(0)

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

    if ret == True:
        hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)

        lower_yellow = np.array([20, 0, 0])
        upper_yellow = np.array([40, 255, 255])

        mask = cv2.inRange(hsv, lower_yellow, upper_yellow)
        res = cv2.bitwise_and(frame, frame, mask=mask)

        img = cv2.medianBlur(res, 5)
        ccimg = cv2.cvtColor(img, cv2.COLOR_HSV2BGR)
        cimg = cv2.cvtColor(ccimg, cv2.COLOR_BGR2GRAY)
        circles = cv2.HoughCircles(cimg, cv2.HOUGH_GRADIENT, 1, 20, param1=50, param2=30, minRadius=20, maxRadius=30)
        if circles is not None:
            print("circle is found")
            circles = np.uint16(np.around(circles))
            for i in circles[0, :]:
                cv2.circle(cimg, (i[0], i[1]), i[2], (0, 255, 0), 2)
                cv2.circle(cimg, (i[0], i[1]), 2, (0, 0, 255), 3)
        cv2.imshow('detected circles', cimg)
        cv2.imshow('res', res)
    else:
        print("Read Failed")

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

cv2.destroyAllWindows()
相关问题