Source
Given 4 pairs of points of the form (x,y)β(xβ²,yβ²), compute the homography matrix
h=βh11βh21βh31ββh12βh22βh32ββtxty1ββ
We write the pre-transformed points as P and the transformed points as Pβ²
P=βx1βx2βx3βx4ββy1βy2βy3βy4βββ,Pβ²=βx1β²βx2β²βx3β²βx4β²ββy1β²βy2β²βy3β²βy4β²βββ
Defining the equation
xβ²=h31βx+h32βy+1h11βx+h12βy+txβyβ²=h31βx+h32βy+1h21βx+h22βy+tyββ
After cross-multiplying and re-arranging:
h11βx+h12βy+txβh31βxxβ²βh32βyxβ²=xβ²h21βx+h22βy+tyβh31βxyβ²βh32βyyβ²=yβ²β
βx1β0x2β0x3β0x4β0βy1β0y2β0y3β0y4β0β10101010β0x1β0x2β0x3β0x4ββ0y1β0y2β0y3β0y4ββ01010101ββx1βx1β²ββx1βy1β²ββx2βx2β²ββx2βy2β²ββx3βx3β²ββx3βy3β²ββx4βx4β²ββx4βy4β²βββy1βx1β²ββy1βy1β²ββy2βx2β²ββy2βy2β²ββy3βx3β²ββy3βy3β²ββy4βx4β²ββy4βy4β²ββββh11βh12βtxh21βh22βtyh31βh32βββ=βx1β²βy1β²βx2β²βy2β²βx3β²βy3β²βx4β²βy4β²βββ
We solve Ah=b for h (i. e. h=Aβ1b).
This gets us the 3x3 h. However, matrix3d
takes a 4x4 matrix. Since we donβt care about z, we can make it just map back to itself:
h=βh11βh21β0h31ββh12βh22β0h32ββ0010βtxty01ββ