# Calculating Affine Transformation matrix from 4 corner points

I'm trying to develop a sudoku solver, using image processing, ocr with neural networks and such. I've got the bare solver working, I can successfully interpret numbers and letters from a picture. All of this is done in GNU Octave. Now I am trying to make it more robust, and I've found this question on stack overflow which greatly helped with most of the image processing. But now I am left with the last part - transforming the single "squares" so that they are uniform and (mostly) square. What I would like to have: A method that from one set of $(X,Y)$ corner coordinates, e.g.:$(73,86), (117,88), (70,127), (115,128)$ would transform the image with interpolation to the set of coordinates, e.g.: $(0,0), (50,0), (0,50), (50,50)$.

I have looked at the functions supplied with octave and there are these possibilities:

but both of them require, for me to know the affine matrix.

Is there a thing I've overlapped with these functions, or could someone here point me in a direction to develop such a function?

If you already have the pairs of corresponding two points from each coordinate, you can use the function fitgeotrans to calculate the transformation matrix.

Once you have got the transformation matrix, the transformation can be done with imwarp.

Note that you are going to use Homography transformation rather than affine transformation in this case (because you have specified corresponding 4 points, which may cause trapezoidal distortion).

The code would be like this...

% assume that the input image is in the variable inputImage.
nPixelsX = 50; % assume that there is square image with 50 pixels for each axes after transformation.
nPixelsY = 50;

movingPoints = [73,86; ...
117,88; ...
70,127; ...
115,128]; % set image's corresponding points
fixedPoint = [0,0; ...
nPixelsY,0; ...
0,nPixelsX; ...
nPixelsY,nPixelsX]; % set ideal coordinate's corresponding points
transformationType = 'Projective';  % this should be homology transformation
tform = fitgeotrans(movingPoints,fixedPoints,transformationType); % make transformation matrix

resultReference = imref2d([nPixelsY, nPixelsX]);
desiredImage = imwarp(inputImage, tform, 'OutputView', resultReference); % transform

• Thank you for your answer, this theoretically answers my question - but your answer is for Matlab(Don't know why, but a moderator added a matlab tag to my post). Octave has not yet implemented the fitgeotrans function.
– Greg
Mar 12 '15 at 9:37
• Ah, I see. Sorry, but I haven't done it yet in Octave... Let's look forward to coming expert person in Octave. Mar 13 '15 at 9:22