最小二乘法来求解矩阵
// 计算Homography矩阵
function calculateHomography(srcPoints, dstPoints) {
if (srcPoints.length !== dstPoints.length || srcPoints.length < 4) {
throw new Error('需要至少四个点进行计算');
}
// 设置矩阵方程 Ax = b
let A = [];
let b = [];
// 构建方程的A矩阵和b向量
for (let i = 0; i < srcPoints.length; i++) {
let x1 = srcPoints[i][0];
let y1 = srcPoints[i][1];
let x2 = dstPoints[i][0];
let y2 = dstPoints[i][1];
// 方程:x2 = H11 * x1 + H12 * y1 + H13
// 方程:y2 = H21 * x1 + H22 * y1 + H23
A.push([-x1, -y1, -1, 0, 0, 0, x1 * x2, y1 * x2]);
A.push([0, 0, 0, -x1, -y1, -1, x1 * y2, y1 * y2]);
b.push(x2);
b.push(y2);
}
// 使用高斯-约旦消元法求解A * h = b
let H = gaussJordan(A, b);
// 构造Homography矩阵
let homographyMatrix = [
[H[0], H[1], H