TypeErroer: NoneType не повторяется - PullRequest
0 голосов
/ 08 июня 2019

Я пытаюсь построить автономную машину для вождения с Raspberry Pi - поэтому я стараюсь учиться на примерах Udacity для Nanodegree.

Следующий код взят из некоторых репозиториев GitHub, и я только что изменил код для работы с PI-CAM. Потому что примеры кода Udacity работают все с видео .mp4.

Когда я пытаюсь запустить следующий код на Raspberry PI с IDE Thonny, иногда он работает в течение нескольких секунд или минут, а иногда даже не запускается.

Вы можете увидеть всю программу здесь .

def draw_lines(img, lines, thickness=5):
    global rightSlope, leftSlope, rightIntercept, leftIntercept
    rightColor=[0,0,255]
    leftColor=[255,0,0]

    #this is used to filter out the outlying lines that can affect the average
    #We then use the slope we determined to find the y-intercept of the filtered lines by solving for b in y=mx+b
    for line in lines:
        for x1,y1,x2,y2 in line:
            slope = (y1-y2)/(x1-x2)
            if slope > 0.3:
                if x1 > 500 :
                    yintercept = y2 - (slope*x2)                    
                    rightSlope.append(slope)
                    rightIntercept.append(yintercept)
                else: None                
            elif slope < -0.3:
                if x1 < 600:
                    yintercept = y2 - (slope*x2)                    
                    leftSlope.append(slope)
                    leftIntercept.append(yintercept)    

     ...               

строки определены в этой части:

def hough_lines(img, rho, theta, threshold, min_line_len, max_line_gap):
    """
    `img` should be the output of a Canny transform.
    """
    lines = cv2.HoughLinesP(img, rho, theta, threshold, np.array([]), minLineLength=min_line_len, maxLineGap=max_line_gap)
    line_img = np.zeros((img.shape[0], img.shape[1], 3), dtype=np.uint8)
    draw_lines(line_img, lines)
    return line_img

def linedetect(img):
    return hough_lines(img, 1, np.pi/180, 10, 20, 100)

Это ошибка, которую я получаю при выполнении кода:

/usr/local/lib/python3.5/dist-packages/numpy/core/fromnumeric.py:3118: RuntimeWarning: Mean of empty slice.
  out=out, **kwargs)
/usr/local/lib/python3.5/dist-packages/numpy/core/_methods.py:85: RuntimeWarning: invalid value encountered in double_scalars
  ret = ret.dtype.type(ret / rcount)
version1_for_PI.py:160: RuntimeWarning: divide by zero encountered in int_scalars
  slope = (y1-y2)/(x1-x2)
Traceback (most recent call last):
  File "/home/pi/Desktop/version-1/version1_for_PI.py", line 244, in <module>
    myline = hough_lines(canny, 1, np.pi/180, 10, 20, 5)
  File "/home/pi/Desktop/version-1/version1_for_PI.py", line 209, in hough_lines
    draw_lines(line_img, lines)
  File "/home/pi/Desktop/version-1/version1_for_PI.py", line 158, in draw_lines
    for line in lines:
TypeError: 'NoneType' object is not iterable

1 Ответ

0 голосов
/ 08 июня 2019

Ваш параметр "lines" - None, который не является "итеративным" типизированным объектом в python (например, списки, наборы и т. Д.). Вы должны либо убедиться, что «строки», которые вы передаете методу, не равны None, либо добавить некоторую логику, чтобы игнорировать это:

if not lines: # means that lines == None
  return 0 # or return something else

Другим хорошим вариантом является захват исключения и его правильная обработка.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...