python - 从点垂直于线
问题描述
所以我有一条不断旋转的线,我想要另一条线垂直于旋转线。问题是它偶尔会指向远离我的旋转线(白色)的垂直(黄色)线。数学是在函数内部完成的,输出看起来像这样。如果加长,我希望这两条线迟早会相交。任何帮助将不胜感激!
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 推荐的。
解决方案
试试这个函数来计算投影点
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
请注意,您的功能失去了正确的方向,而我的项目正确指向任何角度(灰线是箭头的向后延续)
推荐阅读
- typescript - 如何在 TS 中键入装饰器
- rust - 如何将浮点数转换为具有相同字节表示的整数?
- android - Camera2默认控制场景模式为CONTROL_SCENE_MODE_FACE_PRIORITY
- php - 如何在 WooCommerce 商店页面中为未登录用户显示不同的图像?
- python - Selenium (Python):元素不可点击
- typescript - 如何声明必须可以为空或不可定义的类型
- python - 尝试使用 Jupyter Notebooks 从模块导入函数时出现 ModuleNotFoundError
- python - TOP 10 数据框 + 条形图
- python - Python selenium 向下滚动 Instagram 用户喜欢
- python - 这些句子使用 Rasa NLU 是什么意思?