【问题标题】:how can I fix this error: not enough values to unpack (expected 4, got 1)我该如何解决这个错误:没有足够的值来解包(预期 4,得到 1)
【发布时间】:2019-12-27 20:13:27
【问题描述】:

我有代码说:

def averaged_slope_intercept(mage, lines, line=None):
    left_fit = []
    right_fit = []
    x1, y1, x2, y2 = line.reshape(4)

    for line in lines:
        line.reshape(4)
        x1, y1, x2, y2 = line.reshape(4)
        parameters = np.polyfit((x1,x2),(y1,y2), 1)
        print(parameters)
        slope = parameters[0]
        intercept = parameters[1]
        if slope < 0:
            left_fit.append((slope, intercept))
        else:
            right_fit.append((slope, intercept))
    print(left_fit)
    print(right_fit)
    left_fit_avarage = np.average(left_fit, axis=0)
    right_fit_avarage = np.average(right_fit, axis=0)
    print(left_fit_avarage, "left")
    print(right_fit_avarage, "right")
    left_line = make_coordinates(mage, left_fit_average)
    right_line = make_coordinates(mage, right_fit_average)
    return np.array([left_line, right_line])

但我不断收到此错误: : 没有足够的值来解包(预期 4,得到 1) 在线: x1, y1, x2, y2 = line.reshape(4)

课程是@ https://www.youtube.com/watch?v=eLTLtUVuuy4

【问题讨论】:

  • reshape() 返回一个 numpy 数组,而不是 4 个值。
  • 可以调整行为x1, y1, x2, y2 = *line.reshape(4),解构数组赋值。
  • linelines 看起来像什么?它具有reshape 方法这一事实意味着它是一个numpy 数组,但dtypeshape 是什么?

标签: python arrays image numpy


【解决方案1】:

reshape(n) 返回一个 numpy 数组,如提到的@Barmar,这是一个单一的值,但有 4 个项目。您可以通过unpacking the sequence with * 修复此问题并执行sequence assignment

def averaged_slope_intercept(mage, lines, line=None):
    left_fit = []
    right_fit = []
    #x1, y1, x2, y2 = line.reshape(4)                 # Removed

    for line in lines:
        #line.reshape(4)                              # Removed
        x1, y1, x2, y2 = *line.reshape(4)             # Updated
        parameters = np.polyfit((x1,x2),(y1,y2), 1)
        print(parameters)
        slope = parameters[0]
        intercept = parameters[1]
        if slope < 0:
            left_fit.append((slope, intercept))
        else:
            right_fit.append((slope, intercept))
    print(left_fit)
    print(right_fit)
    left_fit_avarage = np.average(left_fit, axis=0)
    right_fit_avarage = np.average(right_fit, axis=0)
    print(left_fit_avarage, "left")
    print(right_fit_avarage, "right")
    left_line = make_coordinates(mage, left_fit_average)
    right_line = make_coordinates(mage, right_fit_average)
    return np.array([left_line, right_line])

【讨论】:

  • 如果数组形状正确,你就不需要* 解包。 a,b,c,d = np.ones((4,3)) 工作得很好。数组在第一维中是可迭代的。我们需要更多地了解line
  • 程序主体被分割成调用函数:lines = cv2.HoughLinesP(cropped_image, 2, np.pi/180, 100, np.array([]), minLineLength=40 , maxLineGap=5) 定义行变量
  • @MNFsoft,我意识到您的代码在语义上不正确,不确定传入的 line 参数将如何帮助您的算法。
猜你喜欢
  • 2016-07-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-10
  • 2018-08-14
  • 2020-02-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多