Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the returned value of cv2.HoughLines of OpenCV for Python need to be accessed with index?

I hope I wrote the question title right because I don't know how to exactly explain it. Consider below's code:

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)

Why it has to be wrote for rho,theta in lines[0]:? By this kind of code, I can only obtain one line. I have tried to remove the indexing in lines but I got ValueError: need more than 1 value to unpack. I have tried to print the returned value and it look something like this:

[[[ 287.            1.97222209]]

[[ 885.            1.20427716]]

[[ 881.            1.22173047]]]

I have kinda solved this problem my making the code look like this:

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

I wonder, what is really happening? Or did I do something wrong here?

like image 686
Hafiz Hilman Mohammad Sofian Avatar asked Jan 22 '16 11:01

Hafiz Hilman Mohammad Sofian


3 Answers

lines=cv2.HoughLines(canny,1,numpy.pi/180,120)
for i in lines:
    # print(i)
    rho=i[0][0]
    theta=i[0][1]
    a=numpy.cos(theta)
    b=numpy.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,255,0),1)
cv2.imshow('ss',img)
like image 94
shravan suthar Avatar answered Sep 27 '22 16:09

shravan suthar


I believe it should be this:

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

this way you loop through all of the values in the lines array, each of which is a line consisting of rho and theta.

It would of course be much bettwe if they structure this as

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

but instead they made it confusing by using the extra nested

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

form.

The line in lines: loops through giving [[ri,ti]] terms, which you can then make into [ri,ti] via line[0], which you then pass into rho and theta.

like image 40
chase Avatar answered Sep 27 '22 15:09

chase


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

This works for me on Python2.7 (Anaconda) and OpenCV3.1.0. There seems to be a mismatch between the example in the online documentation provided by OpenCV (1XnX2) and what it actually returns in the HoughLines function (nX1X2).

like image 31
Fan Zeng Avatar answered Sep 27 '22 17:09

Fan Zeng