Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Precision lost calling cv2.cartToPolar with angleInDegrees set to False

I am using opencv 4.0.0 in python.

When calling the function cv2.cartToPolar with x value to -12 and y value to 0, with parameter angleInDegrees set to False, I'm getting a wrong answer. It should be pi instead I get 3.14159274, which is greater than pi.

x = np.asarray([[-12]], dtype = "float64")
y = np.asarray([[0]], dtype = "float64")

mag, angle = cv2.cartToPolar(x, y, angleInDegrees=True)
print('mag', mag)
print('angle', angle)

>>> mag [[12.]]
>>> angle [[180.]]

x = np.asarray([[-12]], dtype = "float64")
y = np.asarray([[0]], dtype = "float64")

mag, angle = cv2.cartToPolar(x, y, angleInDegrees=False)
print('mag', mag)
print('angle', angle)

>>> mag [[12.]]
>>> angle [[3.14159274]]

I expect the output of 3.14159265.

like image 521
asierrayk Avatar asked Dec 03 '25 09:12

asierrayk


2 Answers

It's an interesting observation. This must have to do with the precision of floating point arithmetic as pointed out by @Sushi. As per the documentation here, the output of cv2.cartToPolar function is given by

enter image description here

x = np.asarray([[-12]], dtype = "float32")
y = np.asarray([[0]], dtype = "float32")

print(cv2.cartToPolar(x, y, angleInDegrees=False)[1])
print(np.radians(np.arctan2(y, x) * 180 / np.pi))

x = np.asarray([[-12]], dtype = "float64")
y = np.asarray([[0]], dtype = "float64")

print(cv2.cartToPolar(x, y, angleInDegrees=False)[1])
print(np.radians(np.arctan2(y, x) * 180 / np.pi))  

output:

[[3.1415927]]
[[3.1415927]]
[[3.14159274]]
[[3.14159265]]  # check this result
like image 146
Anubhav Singh Avatar answered Dec 04 '25 23:12

Anubhav Singh


Please look at the documentation: "The angles are calculated with accuracy about 0.3 degrees". So this is expected behavior. Also your value differs from PI on the 7th decimal place so that may be caused by the precision of floating point arithmetic.

like image 22
Piotr Siekański Avatar answered Dec 04 '25 23:12

Piotr Siekański



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!