Mohamed Nagy Mostafa
Mohamed Nagy Mostafa

Reputation: 353

Draw hough transform lines over an image

I am trying to implement Hough line transform by myself, but I just couldn't do the last step which is drawing high voted thetas/rhos values. I tried to do its math on my own but It remained to get wrong outputs. When I checked some implementations of others, they were always using this approach to transform from Polar to cartesian coordinates in order to find two points.

for r,theta in lines[0]: 

# Stores the value of cos(theta) in a 
a = np.cos(theta) 

# Stores the value of sin(theta) in b 
b = np.sin(theta) 

# x0 stores the value rcos(theta) 
x0 = a*r 

# y0 stores the value rsin(theta) 
y0 = b*r 

# x1 stores the rounded off value of (rcos(theta)-1000sin(theta)) 
x1 = int(x0 + 1000*(-b)) 

# y1 stores the rounded off value of (rsin(theta)+1000cos(theta)) 
y1 = int(y0 + 1000*(a)) 

# x2 stores the rounded off value of (rcos(theta)+1000sin(theta)) 
x2 = int(x0 - 1000*(-b)) 

# y2 stores the rounded off value of (rsin(theta)-1000cos(theta)) 
y2 = int(y0 - 1000*(a)) 

# cv2.line draws a line in img from the point(x1,y1) to (x2,y2). 
# (0,0,255) denotes the colour of the line to be  
#drawn. In this case, it is red.  
cv2.line(img,(x1,y1), (x2,y2), (0,0,255),2) 

The previous code from GeeksForGeeks. What I didn't get are those equations x1 = int(x0 + 1000*(-b)) & y2 = int(y0 - 1000*(a)). By translating these equations as a mathematic form : x1 = r cos(theta) + r (-sin(theta))|| y1 = r sin(theta) + r (cos(theta))

These two equations are just strange to me. 'r cos(theta)' is normal as we transfer from polar to cartesian. However, the next part isn't clear. Could anyone explain the original math behind it?

Upvotes: 0

Views: 1775

Answers (1)

Ahmed M.Naguib
Ahmed M.Naguib

Reputation: 26

(r cos, r sin) is the point closest to the origin on the line. It is not a line equation. To draw a line, u need 2 points. Here, he just moved along line 1000 and -1000 to get two points that are guaranteed to be outside a medium sized image

There are many ways to get line equation. Easiest is: r = x cos + y sin

If x1 = x - t sin
y1 = (1 / sin) (r - x cos + t sin cos)
= y + t cos

He used t=+/-1000 for image size

Upvotes: 1

Related Questions