opencvlinedrawcontour

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


Solution

  • 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.)