sara_123
sara_123

Reputation: 433

Calculating affine or rigid transform base on a set of matched pairs

I have a set of 200 points (x1,y1) in one image that are matched with other 200 points (x2,y2). How can I find the best transform (affine or rigid) that transfers (x1,y1) to (x2,y2)? Any function in MATLAB? Thanks.

Upvotes: 1

Views: 158

Answers (1)

dpmcmlxxvi
dpmcmlxxvi

Reputation: 1302

You can use MATLAB's mldivide or backslash "\" operator to solve for the system of equations using its least squares implementation. Below is a simple approach.

function affinefit

    % Define number of points and a test affine transformation to estimate 
    n = 200;
    A = [0, -1; 1, 0]; % 90 degree rotation about z-axis
    b = [2; 4]; % Offset

    % Generate initial and transformed points points
    xy1 = rand(2, n);
    xy2 = A * xy1 + repmat(b, 1, n);

    % Perform least squares fit on A(1,1), A(1,2), and b(1)
    Ab1 = [xy1', ones(n, 1)] \ xy2(1,:)';

    % Perform least squares fit on A(2,1), A(2,2), and b(2)
    Ab2 = [xy1', ones(n, 1)] \ xy2(2,:)';

    % Extract least squares estimate
    Ae = [Ab1(1:2)'; Ab2(1:2)'];
    be = [Ab1(3); Ab2(3)];

    % Print results
    fprintf('Truth Transformation\n');
    fprintf('A =\n'); disp(A);
    fprintf('b =\n'); disp(b);

    fprintf('Estimated Transformation\n');
    fprintf('A =\n'); disp(Ae);
    fprintf('b =\n'); disp(be);

end

which has the following output

>> affinefit
Truth Transformation
A =
     0    -1
     1     0

b =
     2
     4

Estimated Transformation
A =
    0.0000   -1.0000
    1.0000   -0.0000

b =
    2.0000
    4.0000

Note, there are other things that you should take care of such as outliers in which case you may want to combine this with an outlier detector such as RANSAC.

Upvotes: 1

Related Questions