【问题标题】:TypeError: 'NoneType' object is not iterable CrashTypeError:“NoneType”对象不可迭代崩溃
【发布时间】:2021-11-04 07:50:44
【问题描述】:

代码是:

lines = cv2.HoughLinesP(masked_image, rho, theta, threshold, np.array([]), minLineLength=min_line_len, maxLineGap=max_line_gap)

    # Create an empty black image
    line_image = np.zeros((masked_image.shape[0], masked_image.shape[1], 3), dtype=np.uint8)

    for line in lines: #where the error is happing
        for x1,y1,x2,y2 in line:
            cv2.line(line_image, (x1, y1), (x2, y2), [0, 0, 255], 20)

出现此错误:

Traceback (most recent call last):
  File "linefindinginvideo.py", line 48, in <module>
    for line in lines:
TypeError: 'NoneType' object is not iterable

完整代码请到我的 GitHub https://github.com/jimhoggey/SelfdrivingcarForza/blob/main/lanemarkinginvideo.py

【问题讨论】:

标签: python opencv nonetype


【解决方案1】:

找到解决方案 在 for 语句之前检查变量是否为空的简单语句。

所以我们添加一行

if lines is not None:

这意味着我们的最终语句看起来像这样

lines = cv2.HoughLinesP(masked_image, rho, theta, threshold, np.array([]), minLineLength=min_line_len, maxLineGap=max_line_gap)
line_image = np.zeros((masked_image.shape[0], masked_image.shape[1], 3), dtype=np.uint8)

 if lines is not None: # the fix
      for line in lines:
          for x1,y1,x2,y2 in line:
              cv2.line(line_image, (x1, y1), (x2, y2), [0, 0, 255], 20)

【讨论】:

    【解决方案2】:

    表示这一行:

    cv2.HoughLinesP(masked_image, rho, theta, threshold, np.array([]), minLineLength=min_line_len, maxLineGap=max_line_gap)
    

    返回None,原因是它无法检测到任何行。您将需要调整一些值以使检测正常工作,或者可能是图像中确实没有线条的情况。

    【讨论】:

      猜你喜欢
      • 2012-08-25
      • 1970-01-01
      • 2017-08-29
      • 2016-08-30
      • 2014-11-21
      • 1970-01-01
      相关资源
      最近更新 更多