The underlying implementation principle of the Opencv affine function getAffineTransform

derive

The triangle ABC affine becomes the transformation matrix M of the triangle DEF

Guess matrix M=

[

        [a1,b1,c1],

        [a2,b2,c2]

Mathematical connection of affine transformation

For points A and D

AX*a1+AY*b1+c1=DX

AX*a2+AY*b2+c1=DY

For points B and E

BX*a1+BY*b1+c1=EX

BX*a2+BY*b2+c2=EY

For points C and F

CX*a1+CY*b1+c1=FX

CX*a2+CY*b2+c2=FY

solve

Take the first one for the above mathematical relations

AX*a1+AY*b1+c1=DX

BX*a1+BY*b1+c1=EX

CX*a1+CY*b1+c1=FX

It can be seen that this is a ternary linear equation system. We can solve it with the help of the solve function of the linalg module of the scipy library. You can refer to other materials for its usage, so I won’t repeat it here.

Take the second item for the mathematical connection formula

AX*a2+AY*b2+c1=DY

BX*a2+BY*b2+c2=EY

CX*a2+CY*b2+c2=FY

It is also a ternary linear equation system, which can also be solved with the help of the solve function of the linalg module of the scipy library

verify

According to the coordinates of the above points, use the opencv function and the calculation process we guessed to observe and compare whether the two results are consistent

import numpy as np
import cv2 as cv
import math

AX = 4
AY = 2
BX = 9
BY = 2
CX = 4
CY = 7

DX = 13
DY = 8
EX = 13
EY = 6
FX = 11
FY = 8

ps1 = np.float32([
    [AX, AY],
    [BX, BY],
    [CX, CY]
])
ps2 = np.float32([
    [DX, DY],
    [EX, EY],
    [FX, FY]
])

M = cv.getAffineTransform(ps1, ps2)
print(f"opencv_M=\n{M}")

print()

A = np.array([
    [AX, AY, 1],
    [BX, BY, 1],
    [CX, CY, 1]
])
b1 = np.array([
    [DX],
    [EX],
    [FX]
])
b2 = np.array([
    [DY],
    [EY],
    [FY]
])
from scipy import linalg

r1 = linalg.solve(A, b1)
r2 = linalg.solve(A, b2)
r = np.array([
    r1.T[0],
    r2.T[0]
])
print(f"self_M=\n{r}")

operation result

It can be seen that the results are consistent, and the underlying implementation principle of the function is the same 

Guess you like

Origin blog.csdn.net/qq_36694133/article/details/131243114