simple-homography
Version:
Calculates a homography matrix using exact point correspondences
24 lines (19 loc) • 1.37 kB
text/typescript
import * as Math from 'mathjs'
import { Matrix } from 'mathjs'
//See https://math.stackexchange.com/a/2619023
export function calculateHomography(a1: number[], b1: number[], a2: number[], b2: number[], a3: number[], b3: number[], a4: number[], b4: number[]): Matrix {
let points = Math.matrix([
[-a1[0] , -a1[1] , -1 , 0 , 0 , 0 , a1[0]*b1[0] , a1[1]*b1[0] , b1[0]],
[0 , 0 , 0 , -a1[0], -a1[1], -1 , a1[0]*b1[1] , a1[1]*b1[1] , b1[1]],
[-a2[0] , -a2[1] , -1 , 0 , 0 , 0 , a2[0]*b2[0] , a2[1]*b2[0] , b2[0]],
[0 , 0 , 0 , -a2[0], -a2[1], -1 , a2[0]*b2[1] , a2[1]*b2[1] , b2[1]],
[-a3[0] , -a3[1] , -1 , 0 , 0 , 0 , a3[0]*b3[0] , a3[1]*b3[0] , b3[0]],
[0 , 0 , 0 , -a3[0], -a3[1], -1 , a3[0]*b3[1] , a3[1]*b3[1] , b3[1]],
[-a4[0] , -a4[1] , -1 , 0 , 0 , 0 , a4[0]*b4[0] , a4[1]*b4[0] , b4[0]],
[0 , 0 , 0 , -a4[0], -a4[1], -1 , a4[0]*b4[1] , a4[1]*b4[1] , b4[1]],
[0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 1 ]
])
let pointsInv = Math.inv(points) as Matrix
let hnum = (Math.multiply(pointsInv, [0,0,0,0,0,0,0,0,1])) as Matrix
return Math.reshape(hnum, [3,3]) as Matrix
}