1

Using Python OpenCv, How does one find the Angle of fitLine through an element? I am trying to use debugger and locate, since I do not see it here in documentation ,

rows,cols = img.shape[:2]
[vx,vy,x,y] = cv2.fitLine(cnt, cv2.DIST_L2,0,0.01,0.01)
lefty = int((-x*vy/vx) + y)
righty = int(((cols-x)*vy/vx)+y)
img = cv2.line(img,(cols-1,righty),(0,lefty),(0,255,0),2)

Fitline References:

Fitline Documentation

Open CV Tutorial

Not sure which items to acquire for slope in debugger

enter image description here

mattsmith5
  • 217
  • 1
  • 11
  • 1
    I haven't used it or tried it, but I guess it would be `arctan2((y2-y1)/(x2-x1))` – Mark Setchell Mar 28 '21 at 08:30
  • 2
    @MarkSetchell you have to be acreful using `tan` as if the angle maybe 90 degrees which in undefined for `tan` – DrBwts Mar 28 '21 at 10:07
  • Please don't forget to accept and upvote @DrBwts answer if it is helpful and correct. Click the hollow tick (checkmark) beside the vote tally to accept and the up arrow to upvote. Then other folk know the solution works and other answerers know they don't need to answer and everyone gets the reputation - including you! Thank you. – Mark Setchell Mar 29 '21 at 08:26

1 Answers1

2

As you already have a unit vector that defines the direction of your line [vx, vy] from,

[vx,vy,x,y] = cv2.fitLine(cnt, cv2.DIST_L2,0,0.01,0.01)

Then if you are looking for the angle between your fitted line & the x axis you can use the dot product to get the angle,

import numpy as np

x_axis      = np.array([1, 0])    # unit vector in the same direction as the x axis
your_line   = np.array([vx, vy])  # unit vector in the same direction as your line
dot_product = np.dot(x_axis, your_line)
angle_2_x   = np.arccos(dot_product)
DrBwts
  • 2,798
  • 4
  • 28
  • 45
  • interesting that these answers are slightly different? are they off, just want to understand discrepancy, thanks 1) https://stackoverflow.com/a/13849249/15435022 2) https://stackoverflow.com/a/2827475/15435022 – mattsmith5 Mar 28 '21 at 10:17
  • 1
    @mattsmith5 they are mathematically the same. The only difference is that they convert the vectors into unit vectors. We dont need to do that here as `cv2.fitLine` returns a unit vector (ie it does the conversion for you) & we are using a unit vector to represent the `x` direction. – DrBwts Mar 28 '21 at 10:26
  • 1
    dont forget to click that tick if this answer is working for you so other people can find it easily – DrBwts Mar 28 '21 at 10:50