Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Draw Perpendicular line to a line in opencv

I better explain my problem with an Image

I have a contour and a line which is passing through that contour.
At the intersection point of contour and line I want to draw a perpendicular line at the intersection point of a line and contour up to a particular distance.
I know the intersection point as well as slope of the line.
For reference I am attaching this Image. enter image description here

like image 741
Wazy Avatar asked Dec 29 '11 06:12

Wazy


2 Answers

If the blue line in your picture goes from point A to point B, and you want to draw the red line at point B, you can do the following:

  1. Get the direction vector going from A to B. This would be: v.x = B.x - A.x; v.y = B.y - A.y;
  2. Normalize the vector: mag = sqrt (v.x*v.x + v.y*v.y); v.x = v.x / mag; v.y = v.y / mag;
  3. Rotate the vector 90 degrees by swapping x and y, and inverting one of them. Note about the rotation direction: In OpenCV and image processing in general x and y axis on the image are not oriented in the Euclidian way, in particular the y axis points down and not up. In Euclidian, inverting the final x (initial y) would rotate counterclockwise (standard for euclidean), and inverting y would rotate clockwise. In OpenCV it's the opposite. So, for example to get clockwise rotation in OpenCV: temp = v.x; v.x = -v.y; v.y = temp;
  4. Create a new line at B pointing in the direction of v: C.x = B.x + v.x * length; C.y = B.y + v.y * length; (Note that you can make it extend in both directions by creating a point D in the opposite direction by simply negating length.)
like image 129
user1118321 Avatar answered Nov 16 '22 15:11

user1118321


This is my version of the function :

def getPerpCoord(aX, aY, bX, bY, length):
    vX = bX-aX
    vY = bY-aY
    #print(str(vX)+" "+str(vY))
    if(vX == 0 or vY == 0):
        return 0, 0, 0, 0
    mag = math.sqrt(vX*vX + vY*vY)
    vX = vX / mag
    vY = vY / mag
    temp = vX
    vX = 0-vY
    vY = temp
    cX = bX + vX * length
    cY = bY + vY * length
    dX = bX - vX * length
    dY = bY - vY * length
    return int(cX), int(cY), int(dX), int(dY)
like image 45
CofeDrink68 Avatar answered Nov 16 '22 13:11

CofeDrink68