2

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
  • 540
  • 4
  • 29
  • 67

1 Answers1

3

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
  • 3,470
  • 6
  • 38
  • 62
  • 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
  • 2
    @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