簡體   English   中英

從點垂直於線

[英]Get perpendicular to line from point

所以我有一條不斷旋轉的線,我想要另一條線垂直於旋轉線。 問題是它偶爾會指向遠離我的旋轉線(白色)的垂直(黃色)線。 數學在 function 內部完成,output 看起來像這樣 如果加長,我希望這兩條線遲早會相交。 任何幫助將不勝感激!

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

編輯 1:是用戶 MBo 推薦的。

試試這個 function 來計算投影點

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

似乎您在這里偶爾使用過xor運算符: ^ 2而不是平方**2

請注意,您的 function 失去了正確的方向,而我的投影正確指向任何角度(灰線是箭頭的向后延續)

ideone

它看起來如何

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM