为什么需要使用索引访问Python的OpenCV的cv2.HoughLines的返回值?

Hil*_*man 9 python opencv hough-transform

我希望我写的题目是正确的,因为我不知道如何准确地解释它.考虑下面的代码:

lines = cv2.HoughLines(edges,1,np.pi/180,200)
for rho,theta in lines[0]:
    a = np.cos(theta)
    b = np.sin(theta)
    x0 = a*rho
    y0 = b*rho
    x1 = int(x0 + 1000*(-b))
    y1 = int(y0 + 1000*(a))
    x2 = int(x0 - 1000*(-b))
    y2 = int(y0 - 1000*(a))

    cv2.line(img,(x1,y1),(x2,y2),(0,0,255),2)
Run Code Online (Sandbox Code Playgroud)

为什么要写for rho,theta in lines[0]:?通过这种代码,我只能获得一行.我试图删除索引,lines但我得到了ValueError: need more than 1 value to unpack.我试图打印返回的值,它看起来像这样:

[[[ 287.            1.97222209]]

[[ 885.            1.20427716]]

[[ 881.            1.22173047]]]
Run Code Online (Sandbox Code Playgroud)

我有点解决了这个问题,我的代码看起来像这样:

lines = cv2.HoughLines(edges,1,np.pi/180,200)
for i in range(10):
    for rho,theta in lines[i]:
Run Code Online (Sandbox Code Playgroud)

我想知道,到底发生了什么?或者我在这里做错了什么?

cha*_*ase 5

我相信应该是这样的:

for line in lines:
    rho, theta = line[0]
    ...
Run Code Online (Sandbox Code Playgroud)

这样,您可以遍历lines数组中的所有值,每个值line均由rho和组成theta

如果他们将其构造为

[ [r0,t0], [r1,t1], ... ,[rn,tn] ]

但是相反,他们通过使用额外的嵌套使其变得混乱

[ [[r0,t0]], [[r1,t1]], ... ,[[rn,tn]] ]

形成。

line in lines:通过给循环[[ri,ti]]条款,然后你就可以做成[ri,ti]通过line[0],你再通入rhotheta


小智 0

通过写入,line[0]您可以访问数组的第一个元素。在本例中,第一个元素是另一个包含线参数 rho 和 theta 的数组。cv2.HoughLines这就是函数返回结果的方式。

因此,如果您想迭代 rho 和 theta 的每个组合(即图像中找到的每一行),您可以编写

for [rho, theta] in lines[0]:
    print rho
    print theta
Run Code Online (Sandbox Code Playgroud)