简体   繁体   English

如何使用 NumPy 计算角度?

[英]How to compute angle using NumPy?

I have x and y pixel coordinates that I am using to compute angles.我有用于计算角度的xy像素坐标。 Initially I used the math.atan2 approach but it gave me some issues as I was passing my data as an array .最初我使用math.atan2方法,但是当我将数据作为array传递时,它给了我一些问题。 So now I am using the code below but the values that are being returned are not in the expected range of degrees.所以现在我正在使用下面的代码,但返回的值不在预期的度数范围内。 What am I doing wrong?我究竟做错了什么?

angle1 = np.arctan2(angle1_x, angle1_y)
angle2 = np.arctan2(angle2_x, angle2_y)
degrees = np.degrees(angle1 - angle2)

It seems you're trying to find the angle between two points (x1, y1) and (x2, y2) .看来您正在尝试找到两点(x1, y1)(x2, y2)之间的角度。 For starters, as mentioned in the comments, you have the arguments the wrong way round.对于初学者,如评论中所述,您的论点是错误的。 But even then your current solution doesn't really work.但即便如此,您当前的解决方案也不起作用。

angle1 and angle2 can be anywhere in the range [-pi, pi] so let's assume they are pi and -pi (which although they represent the same value, this is possible due to 0.0 and -0.0 being different floats). angle1angle2可以在[-pi, pi]范围内的任何位置,所以让我们假设它们是pi-pi (虽然它们表示相同的值,但由于0.0-0.0是不同的浮点数,这是可能的)。

This gives a 'difference' of 2*pi which is not quite what you want.这给出了2*pi的“差异”,这不是您想要的。 If we switched them around it would be -2*pi .如果我们切换它们,它将是-2*pi So our values are now in the range [-2*pi, 2*pi] which means that the same answer can be represented by multiple values.所以我们的值现在在[-2*pi, 2*pi]范围内[-2*pi, 2*pi]这意味着相同的答案可以用多个值表示。 How do we fix this?我们如何解决这个问题? By doing通过做

angle_difference = (angle2 - angle1) % np.pi  # range == [0, 2*pi)

You'd need to do a bit more work to get into the range [-pi, pi].您需要做更多的工作才能进入 [-pi, pi] 范围。

angle_difference = angle_difference if angle_difference < np.pi else -2*np.pi + angle_difference

There is another way: https://math.stackexchange.com/questions/227014/find-the-angle-between-two-vectors还有另一种方式: https : //math.stackexchange.com/questions/227014/find-the-angle-between-two-vectors

import numpy as np
from numpy.linalg import norm

v1 = np.array([x1, y1])
v2 = np.array([x2, y2])

angle_difference = np.arccos((v1 @ v2) / (norm(v1) * norm(v2)))  # in range [0, pi]

However since this is symmetric it will give no indication as to the direction of the angle.然而,由于这是对称的,因此不会给出角度方向的指示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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