Skip to main content
 首页 » 编程设计

python之计算两点之间的逆时针角度

2025年02月15日7jpfss

我有一个机器人,红色 LED 和绿色 LED 分别安装在正面和背面。我想计算机器人的头部方向,因为 greenLEd - redLed 矢量指向哪个方向。

我如何对其进行编码,使下图中标记为 1 和 2 的点具有相同的角度,即逆时针 45 度,而点 3 应为 225 度。

我使用了以下脚本,但它给出了错误的结果:

def headDirectionAngle(redLEDCoords, greenLEDCoords, referenceVector): 
    greenRedLEDVector = np.array(greenLEDCoords) - np.array(redLEDCoords) 
    angle = np.math.atan2(np.linalg.det([referenceVector,greenRedLEDVector]),np.dot(referenceVector,greenRedLEDVector)) 
    return np.degrees(angle) 
referenceVector = np.array([0,240]) 

我应该如何进行?感谢您的帮助。

请您参考如下方法:

回到基础,没有 numpy。

atan2已经给你一个逆时针角度,但在 -180 和 180 之间。你可以添加 360 并计算模 360 以获得 0 和 360 之间的角度:

from math import atan2, degrees 
 
def anti_clockwise(x,y): 
    alpha = degrees(atan2(y,x)) 
    return (alpha + 360) % 360 
 
print(anti_clockwise(480, 480)) 
# 45.0 
print(anti_clockwise(-480, -480)) 
# 225.0 

x 应该只是绿色和红色 LED 之间 X 坐标的差异。 y 也是如此。