简体   繁体   中英

Get perpendicular to line from point

So I have a line that rotates constantly and I want to have another line to be perpendicular to the rotating line. The problem is that it will occasionally point the perpendicular (yellow) line away from my rotating line (white). The math is done inside the function and the output looks like this . I would like the two lines to intersect sooner or later if lengthened. Any help would be greatly appreciated!

import cv2
import numpy as np

def perpendicular_finder(line, point):
    x1, y1 = line[0]
    x2, y2 = line[1]
    x3, y3 = point
    if ((y2 - y1) ^ 2 + (x2 - x1) ^ 2) !=0:
        k = ((y2 - y1) * (x3 - x1) - (x2 - x1) * (y3 - y1)) / ((y2 - y1) ^ 2 + (x2 - x1) ^ 2)
        x4 = x3 - k * (y2 - y1)
        y4 = y3 + k * (x2 - x1)
        x4 = np.int(x4)
        y4 = np.int(y4)

        return x4,y4


ballCircle = (200, 200)
purBall = (540,300)
cueX1 = 200
cueY1 = 200
cueX2 = 400
cueY2 = 400
count = 0
while True:
    if count < 400:
        cueX2 -= 1
    elif count < 800:
        cueY2 -= 1
    elif count < 1200:
        cueX2 += 1
    else:
        cueY2 += 1
    if count == 1600:
        count = 0
    else:
        count += 1

    blank = np.zeros((500, 900, 3), np.uint8)  # Create canvas the size of table

    kek = perpendicular_finder((ballCircle, (cueX2,cueY2)), purBall)

    cv2.line(blank, purBall, kek, (0, 255, 255), 1)  # good path
    cv2.circle(blank, ballCircle, 10, (255, 255, 255), -1)  # Ball
    cv2.circle(blank, purBall, 10, (0, 255, 255), -1)  # Purple Ball
    cv2.arrowedLine(blank, (cueX1, cueY1), (cueX2, cueY2), (255, 255, 255), 3)  # Cue

    cv2.imshow("kk", blank)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

Edit 1: This is what user MBo recommended.

Try this function for calculation of projection point

def proj(x1, y1, x2, y2, xp, yp):
    x12 = x2 - x1
    y12 = y2 - y1
    dotp = x12 * (xp - x1) + y12 * (yp - y1)
    dot12 = x12 * x12 + y12 * y12
    if dot12:
        coeff = dotp / dot12
        lx = x1 + x12 * coeff
        ly = y1 + y12 * coeff
        return lx, ly
    else:
        return None

Seems you have occasionally used xor operator here: ^ 2 instead of squaring **2

Note that your function looses right direction, while mine projects point correctly for any angle (grey line is backward continuation of arrow)

ideone

How it looks

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM