hevele
hevele

Reputation: 933

Determining 2D Affine Transformation of Images

I am having a problem determining the affine transformation matrix of below image.

Original Image:

enter image description here

Affine Transformed Image:

enter image description here

I determined 2 points on the images to solve affine transformation matrix, but the results I get does not convert original to desired.

The code is below, it first solves the matrix and use it to transform original to transformed version:

% Pixel values
p1_aff = [164; 470]; 
p1_nor = [1; 512];
p2_aff = [470; 164];
p2_nor = [512; 1];
%p3_aff = [131;68];
%p3_nor = [166;61];
%p4_aff = [328;90];
%p4_nor = [456;59];

%Transformation matrix
syms a11 a12 a21 a22;
A = [a11 a12; a21 a22];

%Solving matrix
[Sx, Sy, Sz, Sk] = solve(A*p1_nor==p1_aff, A*p2_nor==p2_aff);
a11_d = double(Sx);
a12_d = double(Sy);
a21_d = double(Sz);
a22_d = double(Sk);

lena = imread('lena512.png');
new_aff = uint8(zeros(size(lena)));

for i = 1:size(lena,1)
    for j = 1:size(lena,2)
        % Applying affine transformation
        new_coord = [a11_d a12_d 0; a21_d a22_d 0; 0 0 1]*[i; j; 1];

        % Nearest-Neighbor interpolation for placing new pixels
        if(round(new_coord(1)) > 0 && round(new_coord(2)) > 0)
            new_aff(round(new_coord(1)),round(new_coord(2))) = lena(i,j);
        end
    end
end

imwrite(new_aff, 'lenaAffine_new.png');

At the end of above code, I get this image: enter image description here

Does anyone understand what is wrong here? I am going crazy.

Upvotes: 1

Views: 6659

Answers (1)

Shai
Shai

Reputation: 114796

Two corresponding points are not enough to determine affine transformation. You need at least 6 matches (If I'm not mistaken).

Use cpselect gui to select corresponding points:

>> [input_points, base_points] = cpselect(oim2, oim1, 'Wait', true);

Then you can transform using:

>> T = cp2tform( input_points, base_points, 'affine' );
>> aim2 = tformarray( oim2, T, makeresampler('cubic','fill'), [2 1], [2 1], size(oim1(:,:,1)'), [], 0 );

Upvotes: 4

Related Questions