对于将来遇到类似问题的任何人,scipy 与 pytorch 仿射变换的问题是 scipy 在 (0, 0, 0) 周围应用变换,而 pytorch 在图像/体积的中间应用它。
例如,我们取参数:
euler_angles = [ea0, ea1, ea2]
translation = [tr0, tr1, tr2]
scale = [sc0, sc1, sc2]
并创建以下变换矩阵:
# Rotation matrix
R_x(ea0, ea1, ea2) = np.array([[1, 0, 0, 0],
[0, math.cos(ea0), -math.sin(ea0), 0],
[0, math.sin(ea0), math.cos(ea0), 0],
[0, 0, 0, 1]])
R_y(ea0, ea1, ea2) = np.array([[math.cos(ea1), 0, math.sin(ea1), 0],
[0, 1, 0, 0],
[-math.sin(ea1), 0, math.cos(ea1)], 0],
[0, 0, 0, 1]])
R_z(ea0, ea1, ea2) = np.array([[math.cos(ea2), -math.sin(ea2), 0, 0],
[math.sin(ea2), math.cos(ea2), 0, 0],
[0, 0, 1, 0],
[0, 0, 0, 1]])
R = R_x.dot(R_y).dot(R_z)
# Translation matrix
T(tr0, tr1, tr2) = np.array([[1, 0, 0, -tr0],
[0, 1, 0, -tr1],
[0, 0, 1, -tr2],
[0, 0, 0, 1]])
# Scaling matrix
S(sc0, sc1, sc2) = np.array([[1/sc0, 0, 0, 0],
[0, 1/sc1, 0, 0],
[0, 0, 1/sc2, 0],
[0, 0, 0, 1]])
如果你有一个大小为 (100, 100, 100) 的体积,围绕体积中心的 scipy 变换需要先将体积中心移动到 (0, 0, 0),然后再将其移回(50, 50, 50) 在应用 S、T 和 R 之后。定义:
T_zero = np.array([[1, 0, 0, 50],
[0, 1, 0, 50],
[0, 0, 1, 50],
[0, 0, 0, 1]])
T_centre = np.array([[1, 0, 0, -50],
[0, 1, 0, -50],
[0, 0, 1, -50],
[0, 0, 0, 1]])
那么围绕中心的 scipy 变换是:
transform_scipy_centre = T_zero.dot(T).dot(S).dot(R).T_centre
在pytorch中,参数有一些细微的差别。
翻译定义在-1和1之间。它们的顺序也不同。以相同的(100,100,100)体积为例,pytorch中的平移参数由下式给出:
# Note the order difference
translation_pytorch = =[tr0_p, tr1_p, tr2_p] = [tr0/50, tr2/50, tr1/50]
T_p = T(tr0_p, tr1_p, tr2_p)
比例参数的顺序不同:
scale_pytorch = [sc0_p, sc1_p, sc2_p] = [sc2, sc0, sc1]
S_p = S(sc0_p, sc1_p, sc2_p)
欧拉角是最大的区别。为了得到等价的变换,首先参数是负的并且顺序不同:
# Note the order difference
euler_angles_pytorch = [ea0_p, ea1_p, ea2_p] = [-ea0, -ea2, -ea1]
R_x_p = R_x(ea0_p, ea1_p, ea2_p)
R_y_p = R_y(ea0_p, ea1_p, ea2_p)
R_z_p = R_z(ea0_p, ea1_p, ea2_p)
旋转矩阵的计算顺序也不同:
# 注意顺序差异
R_p = R_x_p.dot(R_z_p).dot(R_y_p)
考虑到所有这些因素,scipy 转换为:
transform_scipy_centre = T_zero.dot(T).dot(S).dot(R).T_centre
相当于pytorch变换:
transform_pytorch = T_p.dot(S_p).dot(R_p)
我希望这会有所帮助!