仿射变换是图形学中经常用到的方法,通常但是仿射变换的系数是未知的,需要找到变换前后的三对对应点进行求解。
python
from affine import Affine
import numpy as np
参考文献
矩阵最小二乘法求解仿射变换矩阵
python
def solve_affine(init_points, goal_points) -> Affine:
# 分别整理成上面分析的6x6和6x1的矩阵
# 先定义变量保留6个坐标的值
(ax, ay), (bx, by), (cx, cy) = init_points
(ax1, ay1), (bx1, by1), (cx1, cy1) = goal_points
A = np.array([
[ax, ay, 1, 0, 0, 0],
[0, 0, 0, ax, ay, 1],
[bx, by, 1, 0, 0, 0],
[0, 0, 0, bx, by, 1],
[cx, cy, 1, 0, 0, 0],
[0, 0, 0, cx, cy, 1]
])
B = np.array([ax1, ay1, bx1, by1, cx1, cy1]).reshape(6, 1) # 比手写6X1矩阵要省事
M = np.linalg.inv(A.T @ A) @ A.T @ B # 套公式
M=M.flatten().tolist()
return Affine(*M) #转换成Affine对象
python
A = [[0,0], [50, 0], [50, 50]]
B = [[30, 30], [130, 30], [130, 130]]
transform=solve_affine(A,B)
for a,b in zip(A,B):
print(a,b,transform*a)