# -*- coding: utf-8 -*-
import sys
import cv2
import numpy as np
def polar(I,center,r,theta=(0,360),rstep=1.0,thetastep=360.0/(180*8)):
#获取极坐标变换中心坐标
cx,cy=center
#获取距离的最小和最大范围
minr,maxr=r
#获取角度最小范围
mintheta,maxtheta=theta
#输出图像的高宽
h=int((maxr-minr)/rstep)+1
w=int((maxtheta-mintheta)/thetastep)+1
O=125*np.ones((h,w),I.dtype)
#极坐标变换
r=np.linspace(minr,maxr,h)#生成等差数列,minr起始,maxr终止,生成h个
r=np.tile(r,(w,1))
r=np.transpose(r)#r转置
theta=np.linspace(mintheta,maxtheta,w)
theta=np.tile(theta,(h,1))
x,y=cv2.polarToCart(r,theta,angleInDegrees=True)
#print("x:\n",x)
#print(x.shape)
#最近邻插值
for i in range(h):
#print('')
for j in range(w):
px=int(round(x[i][j])+cx)
py=int(round(y[i][j])+cy)
#print(px)
if ((px>=0 and px<=w-1) and (py>=0 and py<=h-1)):
#print(I[py][px])
#print("j:",j)
O[i][j]=I[py][px]
return O
if __name__=="__main__":
#笛卡尔坐标系转换为极坐标系
x=np.array([[0,1,2],[0,1,2],[0,1,2]],np.float64)-1#以(1,1)为中心转化(0,0),(1,0)等坐标,故-1
y=np.array([[0,0,0],[1,1,1],[2,2,2]],np.float64)-1
r,theta=cv2.cartToPolar(x,y,angleInDegrees=True)#angleInDegrees=true:角度;false:弧度
print('r:',r,'\ntheta:',theta)
#极坐标转化笛卡尔坐标
x,y=cv2.polarToCart(r,theta,angleInDegrees=True)
print('x\n:',x+1,'\ny\n:',y+1)
#tile(a,(m,n))函数,将a分别在垂直和水平方向复制m和n次
a=r
b=np.tile(a,(2,3))
print('a:\n',a,'\nb:\n',b)
if len(sys.argv)>1 :
img = cv2.imread(sys.argv[1],0)
else:
print('None')
h,w=img.shape[:2]
cx,cy=530,280
cv2.circle(img,(int(cx),int(cy)),20,(255,0,0),3)
O=polar(img,(cx,cy),(0,500))
O=cv2.flip(O,0)
cv2.imshow('img',img)
cv2.imshow('O',O)
cv2.waitKey(0)
cv2.destroyAllWindows()
'''
r: [[1.41421356 1. 1.41421356]
[1. 0. 1. ]
[1.41421356 1. 1.41421356]]
theta: [[224.990448 270. 315.009552 ]
[180. 0. 0. ]
[135.009552 90. 44.99045563]]
x
: [[-1.66715818e-04 1.00000000e+00 2.00016672e+00]
[ 0.00000000e+00 1.00000000e+00 2.00000000e+00]
[-1.66715818e-04 1.00000000e+00 2.00016655e+00]]
y
: [[1.66750047e-04 0.00000000e+00 1.66750047e-04]
[1.00000000e+00 1.00000000e+00 1.00000000e+00]
[1.99983325e+00 2.00000000e+00 1.99983342e+00]]
a:
[[1.41421356 1. 1.41421356]
[1. 0. 1. ]
[1.41421356 1. 1.41421356]]
b:
[[1.41421356 1. 1.41421356 1.41421356 1. 1.41421356
1.41421356 1. 1.41421356]
[1. 0. 1. 1. 0. 1.
1. 0. 1. ]
[1.41421356 1. 1.41421356 1.41421356 1. 1.41421356
1.41421356 1. 1.41421356]
[1.41421356 1. 1.41421356 1.41421356 1. 1.41421356
1.41421356 1. 1.41421356]
[1. 0. 1. 1. 0. 1.
1. 0. 1. ]
[1.41421356 1. 1.41421356 1.41421356 1. 1.41421356
1.41421356 1. 1.41421356]]
'''
原图:
修改后: