在R中变换图像的极坐标

7
我正在尝试将R中表示为矩阵的图像转换为以0,0(左上角)为原点的极坐标空间。给定215x215矩阵x,它看起来像:
x0 = as.vector(col(x)) y0 = as.vector(row(x))
r = sqrt((x0^2) + (y0^2)) # x a = atan(y0/x0) # y m = as.matrix(data.frame(y=a, x=r))
m = round(m) m[m>215] = NA m[m==0] = NA
xn = x[m] xn = matrix(xn, 215, 215)
然而,xn看起来只是这样:
当我期望的是这个:
你知道我做错了什么吗?
1个回答

10

角度计算存在问题: atan 返回的是弧度制的角度。 如果四舍五入,将会失去大量信息...

尝试使用:

a = atan(y0/x0) * 215 / (pi/2)

变换后的图像

这不是您所期望的图像,显然是反向变换,中心在图像中央。

# Load the image
library(png)
library(RCurl)
d <- readPNG( getBinaryURL( "http://i.stack.imgur.com/rMR3C.png" ) )
image(d, col=gray(0:255/255))

# Origin for the polar coordinates
x0 <- ncol(d)/2
y0 <- nrow(d)/2

# The value of pixel (i,j) in the final image 
# comes from the pixel, in the original image, 
# with polar coordinates (r[i],theta[i]).
# We need a grid for the values of r and theta.
r <- 1:ceiling(sqrt( max(x0,nrow(d))^2 + max(y0,ncol(d))^2))
theta <- -pi/2 + seq(0,2*pi, length = 200)
r_theta <- expand.grid(r=r, theta=theta)

# Convert those polar coordinates to cartesian coordinates:
x <- with( r_theta, x0 + r * cos(theta) )
y <- with( r_theta, y0 + r * sin(theta) )
# Truncate them
x <- pmin( pmax( x, 1 ), ncol(d) )
y <- pmin( pmax( y, 1 ), nrow(d) )

# Build an empty matrix with the desired size and populate it
r <- matrix(NA, nrow=length(r), ncol=length(theta))
r[] <- d[cbind(x,y)]
image(r, col=gray(0:255/255))

谢谢,很棒的答案!您可以解释一下代码的每个部分是在做什么吗?我对r和theta的公式以及sin/cos值的乘法有些困惑。再次感谢。 - Omar Wagih
1
我已经简化了代码并添加了一些注释。 - Vincent Zoonekynd

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接