0

我正在尝试使用 Raspberry Pi 构建自动驾驶汽车 - 因此我尝试从 Udacity 的 Nanodegree 示例中学习。

以下代码来自一些 GitHub 存储库,我只是更改了代码以使用 PI-CAM。因为 Udacity 示例代码适用于所有 .mp4 视频。

当我尝试使用 Thonny IDE 在 Raspberry PI 上运行以下代码时,有时它会运行几秒钟或一分钟,有时甚至不会开始运行。

你可以在这里看到整个程序。

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

4

1 回答 1

0

您的“行”参数是 None - 它不是 python 中的“可迭代”类型对象(例如列表、集合等)。您应该确保传递给该方法的“行”不是 None - 或者添加一些逻辑来忽略它:

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

另一个不错的选择是捕获异常并正确处理它。

于 2019-06-08T10:43:26.347 回答