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

问题描述 投票:7回答:5

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

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)

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

[[[ 287.            1.97222209]]

[[ 885.            1.20427716]]

[[ 881.            1.22173047]]]

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

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

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

python opencv hough-transform
5个回答
3
投票

我相信它应该是这样的:

for line in lines:
    rho, theta = line[0]
    ...

这样你就可以遍历lines数组中的所有值,每个数组都是由linerho组成的theta

如果将它们构造成这样的话,那当然会好得多

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

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

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

形成。

line in lines:循环通过给[[ri,ti]]术语,然后你可以通过[ri,ti]进入line[0],然后你传递到rhotheta


2
投票

问题和答案是指这个基于opencv 3.0.0的tutorial。在openCV 3.2.0中,由houghlines返回的嵌套列表是一个nX1X2数组(其中n是行数),访问rho和theta的正确方法可以在这个tutorial中找到。

所以..根据第一个教程:“Lines”是一个多维1XnX2数组(ndarray),其中n是检测到的行数。

第一个数组只包含一个元素,行[0](nX2数组),这是你的行列表(你只需要遍历这个)。

在第二级,您有行[0] [0],行[0] [1],...,行[0] [n]。 (这是你的线)

最后,在第3级,你有行[0] [n] [0]和行[0] [n] [1],它们是每行的rho和theta值。您的解决方案无法正常工作,因为没有行[1]数组!

您可以将其添加到代码中并查看其打印内容。

print lines.shape
print lines[0].shape
print lines[0][0].shape

1
投票
for line in lines:
    rho, theta = line[0]
    a = np.cos(theta)
    b = np.sin(theta)

这适用于Python2.7(Anaconda)和OpenCV3.1.0。 OpenCV(1XnX2)提供的在线文档中的示例与HoughLines函数(nX1X2)中实际返回的示例之间似乎存在不匹配。


0
投票

通过编写line[0],您可以访问数组的第一个元素。在这种情况下,第一个元素是包含行参数rho和theta的另一个数组。这就是cv2.HoughLines函数返回结果的方式。

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

for [rho, theta] in lines[0]:
    print rho
    print theta

0
投票

这对我有用

for l in lines:
    rho = l[0][0]
    theta = l[0][1]
    a = np.cos(theta)
© www.soinside.com 2019 - 2024. All rights reserved.