如何在某些点固定的情况下获得仿射变换



例如,我在一个坐标系中有4个点,在另一个坐标系统中有4点,如果我以朴素的方式估计仿射变换,则角点[points 1,4]将不会精确地扭曲到另一坐标系中的相应角点。

如何在某些点应该在另一个坐标系中的对应点上翘曲的限制下获得仿射变换?

据我所知,当已知4个特定点的图像时,您需要恢复仿射变换。我想,下面的代码可能会对你有所帮助(很抱歉代码风格不好——我是数学家,而不是程序员(

import numpy as np
# input data
ins = np.array([[1, 1, 2], [2, 3, 0], [3, 2, -2], [-2, 2, 3]]) # <- primary system
out = np.array([[0, 2, 1], [1, 2, 2], [-2, -1, 6], [4, 1, -3]]) # <- secondary system
p = np.array([1, 2, 3]) #<- transform this point
# finding transformation
l = len(ins)
e = lambda r,d: np.linalg.det(np.delete(np.vstack([r, ins.T, np.ones(l)]), d, axis=0))
M = np.array([[(-1)**i * e(R, i) for R in out.T] for i in range(l+1)])
A, t = np.hsplit(M[1:].T/(-M[0])[:,None], [l-1])
t = np.transpose(t)[0]
# output transformation
print("Affine transformation matrix:n", A)
print("Affine transformation translation vector:n", t)
# unittests
print("TESTING:")
for p, P in zip(np.array(ins), np.array(out)):
image_p = np.dot(A, p) + t
result = "[OK]" if np.allclose(image_p, P) else "[ERROR]"
print(p, " mapped to: ", image_p, " ; expected: ", P, result)
# calculate points
print("CALCULATION:")
P = np.dot(A, p) + t
print(p, " mapped to: ", P)

这段代码演示了如何将仿射变换恢复为矩阵+向量,并测试初始点是否映射到它们应该映射的位置。你可以用谷歌colab测试这个代码,这样你就不必安装任何东西。

关于该代码背后的理论:它基于"仿射映射单纯形的初学者指南"中提出的方程,矩阵恢复在"正则表示法的恢复"一节中进行了描述,精确仿射变换所需的点数在"我们需要多少点?"一节进行了讨论。同一位作者出版了"关于仿射映射单纯形的工作簿",其中包含了许多此类实用示例。

最新更新