Search code examples
pythonopencvimage-processinghough-transform

Traffic Light Detection by using opencv


 import cv2 import numpy as np
 cap = cv2.VideoCapture(0)
while True:
    _, frame = cap.read() # frame olarak goruntuyu aldık
    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)
    cimg = cv2.cvtColor(img, cv2.COLOR_HSV2BGR)
    cimg = cv2.cvtColor(cimg, cv2.COLOR_BGR2GRAY)
    circles = cv2.HoughCircles(cimg, cv2.HOUGH_GRADIENT, 1, 20,                  
                     param1=50, param2=30, minRadius=20, maxRadius=30)
    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)
    k = cv2.waitKey(5) & 0xFF
    if k == 27:
        break
cv2.destroyAllWindows()

This is my codes. I want to detect traffic light on live stream by using image processing . Firstly I will detect yellow colour, after that I will find circle on mask image . I think, The error is occuring at the HoughCircles parameters. But there is a error called:

Error: Traceback (most recent call last): File "/home/yavuzhan/PythonProgramlama/venv/lib/python3.5/site-packages/numpy/core/fromnumeric.py", line 52, in _wrapfunc return getattr(obj, method)(*args, **kwds) AttributeError: 'NoneType' object has no attribute 'round'

During handling of the above exception, another exception occurred:

Traceback (most recent call last): File "/media/yavuzhan/DATA/2017-2018/Otonom Araç Projesi/Dosya/Otonom Araç Yazılım/renkalgilama.py", line 30, in circles = np.uint16(np.around(circles))


Solution

  • You were getting AttributeError: 'None Type' object has no attribute 'round' because circles in circles = cv2.HoughCircles(cimg, cv2.HOUGH_GRADIENT, 1, 20, param1=50, param2=30, minRadius=20, maxRadius=30) was empty. This is because cv2.HoughCircles didn't find any circles. You should put a check for circles like if circles is not None before using it later.

    PS. Try to tune the parameters so that cv2.HoughCircles finds circles you can work with. And try to read the docs to pin point the problem yourself.