How to convert coordinate system with Python-OpenCV

created at 07-02-2021 views: 3

The example below uses OpenCV to convert  coordinate system in Python.

Cartesian to polar coordinate

#coding=utf-8
#Polar coordinate transformation is (x, y) converted to (r, theta), that is (radius, angle)
import math
import cv2
import numpy as np
x=[2,4]
center=[4,0]
r=math.sqrt(math.pow(x[0]-center[0],2)+math.pow(x[1]-center[1],2))
theta=math.atan2(x[1]-center[1],x[0]-center[0])/math.pi*180#convert to angle
print r,theta
#opencv also provides functions for polar coordinate transformation
x1=np.array([[0,1,2],[0,1,2],[0,1,2]],np.float32)
y1=np.array([[0,0,0],[1,1,1],[2,2,2]],np.float32)
#The real conversion coordinates are (0,0), (1,0), (2,0), (0,1), (1,1). . . . ,# The transformation center is the origin, if you want to be (2,3), you need x1-2,y1-3
# the default center is (0,0),if you want to change it to (2,3),you should let x minus 2 and y minus 3
#when the angleInDegrees=True, that means the return is measured by angle, if not, it is radian.
r1,theta1=cv2.cartToPolar(x1,y1,angleInDegrees=True)
print r,theta

Inverse conversion

The following is the inverse transformation, that is, polar coordinates are changed to Cartesian coordinates. (r,theta) is transformed into (x,y)

r=np.array([1,2,1],np.float32)
theta=np.array([30,45,90],np.float32)
x,y=cv2.polarToCart(r,theta,angleInDegrees=True)
print x,y
Please log in to leave a comment.