笛卡尔坐标与极坐标之间的转换.希望结果是积极的



我有几个点需要将它们从笛卡尔坐标隐藏到极坐标。但对于某些点,我得到的结果是负值。

例如,系统的原点或中心是(50,50(,而我要隐蔽的点是(10,43(。我从代码中得到的角度是 -170.07375449,但我希望角度是 189.92624551。(希望转换后的所有角度都在0~360度之间(

我如何解决这个问题?

谢谢!!!

import numpy as np
points = np.array([(10, 43), (10, 44), (10, 45), (10, 46), (10, 47)])
#Set the center (origin) at (50, 50). Not (0, 0)
def cart_to_pol(coords, center = [50,50], deg = True):
complex_format = np.array(coords, dtype = float).view(dtype = np.complex) -
np.array(center, dtype = float).view(dtype = np.complex)
# return np.abs(complex_format).squeeze(), np.angle(complex_format, deg = deg).squeeze()
return np.angle(complex_format, deg=deg).squeeze()
print(cart_to_pol(points))

您可以使用np.where将 360 度添加到负角度:

import numpy as np
points = np.array([(10, 43), (10, 44), (10, 45), (10, 46), (10, 47)])
#Set the center (origin) at (50, 50). Not (0, 0)
def cart_to_pol(coords, center = [50,50], deg = True):
complex_format = np.array(coords, dtype = float).view(dtype = np.complex) -
np.array(center, dtype = float).view(dtype = np.complex)
angles = np.angle(complex_format, deg=deg).squeeze()
summand = 360 if deg else 2*np.pi
return np.where(angles < 0, angles+summand, angles)
print(cart_to_pol(points))

输出:

[189.92624551 188.53076561 187.12501635 185.71059314 184.28915333]

请注意,此处不需要复数。arctan2(y, x)计算所需的角度。要获取距离:np.linalg.norm(diff_with_center, axis=-1)

def cart_to_pol(coords, center=[50, 50], deg=True):
conversion = 180 / np.pi if deg else 1
diff_with_center = points - center
angles = np.arctan2(diff_with_center[:, 1], diff_with_center[:, 0])
return conversion * np.where(angles < 0, angles + 2*np.pi, angles)

如果需要将 [-180; 180] 角度转换为 [0; 360],可以使用以下代码:

def convert_angle(angle):
return (angle + 360) % 360

在这里结合其他一些解决方案...

如果您将原点和/或点指定为浮点数,则可以使用视图将它们作为复数进行操作,然后简单地返回角度模 360 度:

points = points - origin    
np.angle(points.view(np.complex), deg=True) % 360
>>> array([[189.92624551],
[188.53076561],
[187.12501635],
[185.71059314],
[184.28915333]])

或者,对于就地操作,假设点已经是浮点数:

np.subtract(points, origin, out=points)
v = points.view(np.complex)
np.arctan2(v.imag, v.real, out=v.real)
np.degrees(v.real, out=v.real)
np.mod(v.real, 360, out=v.real)
print(points[0])  # or print(v.real)
>>> array([[189.92624551],
[188.53076561],
[187.12501635],
[185.71059314],
[184.28915333]])

在这种情况下,我们不能使用angle,因为没有out选项,但我们可以通过视图以点 [0] 就地计算 arctan2。这不会比原始(浮点(点数组使用更多的内存,虽然我没有计时,但应该不需要更多的操作来计算。

相关内容

最新更新