TensorFlow中逆对数极坐标变换实现错误排查求助
对数极坐标逆变换结果异常问题排查
我已实现对数极坐标变换(LPT)及其逆变换,正向变换运行正常,但逆变换输出图像结果不正确。推测问题出在网格坐标的归一化环节,但无法定位具体原因。
正向变换代码
def log_polar_transform(x, radius_factor = tf.sqrt(2.)): b, h, w, c = x.shape grid = make_grid(h, w) #(2, hw), represent log-polar coordinate system grid = tf.repeat(grid[None, ...], b, axis=0) #(b, 2, hw) X, Y = grid[:, 0], grid[:, 1] #theta theta = (Y + 1) * math.pi #[0, 2pi] #radius maxR = max(h, w) * radius_factor r = tf.exp((X + 1)/2 * tf.math.log(maxR)) #[1, h] r = (r-1)/(maxR -1) #[0, h]-->[0, 1] r = r * (maxR/h) #scale factorize #map to cartesian coordinate system xs = tf.reshape(r * tf.math.cos(theta), [b, h, w]) ys = tf.reshape(r * tf.math.sin(theta), [b, h, w]) output = interpolate(x, xs, ys) output = tf.reshape(output, [b, h, w, c]) return output
原逆变换代码
def inverse_log_polar_transform(x): b, h, w, c = x.shape grid = make_grid(h, w) grid = tf.repeat(grid[None, ...], b, axis=0) #(b, 2, hw) X, Y = grid[:, 0], grid[:, 1] rs = tf.sqrt(X**2 + Y **2)/tf.sqrt(2.) ts = (tf.atan2(-Y, -X))/math.pi #[-1., 1.] rs = tf.reshape(rs, [b, h, w]) ts = tf.reshape(ts, [b, h, w]) output = interpolate(x, rs, ts) output = tf.reshape(output, [b, h, w, c]) return output
问题根源
原逆变换完全没有对应正向LPT的数学映射逻辑,只是对网格坐标做了简单的极坐标转换,和正向变换的对数映射、坐标缩放、角度定义完全脱节,导致采样坐标错误。
修正后的逆变换代码
def inverse_log_polar_transform(x, radius_factor = tf.sqrt(2.)): b, h, w, c = x.shape maxR = max(h, w) * radius_factor grid = make_grid(h, w) # 对应原图的笛卡尔归一化坐标[-1,1]×[-1,1] grid = tf.repeat(grid[None, ...], b, axis=0) X, Y = grid[:, 0], grid[:, 1] # 把归一化坐标转换为原图空间的中心坐标系 x_cart = X * (w / 2) y_cart = Y * (h / 2) # 计算原图空间的极径,并反向推导对数极坐标的径向归一化坐标 r = tf.sqrt(x_cart**2 + y_cart**2) r = r * (h / maxR) # 反向正向的缩放步骤 r = r * (maxR - 1) + 1 # 反向归一化步骤 r = tf.maximum(r, 1e-6) # 避免log(0)报错 rs = (2 * tf.math.log(r) / tf.math.log(maxR)) - 1 # 反向对数映射 # 计算原图空间的极角,并反向推导对数极坐标的角度归一化坐标 theta = tf.atan2(y_cart, x_cart) # 范围[-π, π] theta = tf.where(theta < 0, theta + 2 * math.pi, theta) # 转换为[0, 2π] ts = (theta / math.pi) - 1 # 对应正向的theta=(Y+1)*π的逆运算 rs = tf.reshape(rs, [b, h, w]) ts = tf.reshape(ts, [b, h, w]) output = interpolate(x, rs, ts) output = tf.reshape(output, [b, h, w, c]) return output
关键修正说明
- 完整逆运算链:严格按照正向变换的步骤反向推导,从原图笛卡尔坐标还原出对数极坐标的归一化采样坐标
- 角度匹配:修正极角的计算方向和范围,和正向变换的θ定义保持一致,确保角度采样正确
- 边界处理:添加r=0的防护,避免对数运算出现无效值
- 参数一致性:保留正向变换的
radius_factor参数,保证前后变换的参数统一
内容的提问来源于stack exchange,提问作者Tom Huang
相关产品推荐
相关产品推荐

