% ----------------------------------------------------------------------
% - CSE 486
% - Project 1
% - Group 8
% - idg101, adi102, jlm522
% ----------------------------------------------------------------------

% Read in image.
I = imread('giraffe.jpg', 'jpg');

% Translate image 16 pixels along X and Y axis.
T = [ 1 0 0 -16;
       0 1 0  16;
       0 0 1  0;
       0 0 0  1];

% Rotate image ccw 15 degrees.
angle = (-15*pi/180);
R =     [cos(angle)   sin(angle)  0 0;
        -sin(angle)   cos(angle)  0 0;
        0             0           1 0;
        0             0           0 1];

% Create ouput image.
M = R*T;
for x_index = -127:128
     for y_index = -127:128
        OutputVector = inv(M) * [x_index; y_index; 0; 1];
        x = OutputVector(1);
        y = OutputVector(2);
    
        % Nearest Neighborhood Interpolation (nni)
        x_nni = round(x);
        y_nni = round(y);
        
        % Linear Interpolation (li)
        r = floor(x);
        c = floor(y);
        a = x - r; b = y -c;
            
        % Ensure coordinates of I are valid.
        if (x_nni > 128 | x_nni < -127 | y_nni > 128 | y_nni < -127)
            O_nni(x_index + 128, y_index + 128) = 255;
        else
            % Nearest Neighborhood Interpolation
            O_nni(x_index + 128, y_index + 128) = I(x_nni + 128, y_nni + 128);
        end
  
        % Linear Interpolation
        % Ensure coordinates of I are valid.
        if (r > 128 | r < -127 | c > 128 | c < -127)
            point_north = 255;
        else
            point_north = double(I(r + 128, c + 128));
        end
        if (r + 1 > 128 | r + 1 < -127 | c > 128 | c < -127)
            point_east = 255;
        else
            point_east = double(I(r + 1 + 128, c + 128));
        end
        if (r > 128 | r < -127 | c + 1 > 128 | c + 1 < -127)
            point_south = 255;
        else
            point_south = double(I(r + 128, c + 1 + 128));    
        end
        if (r + 1 > 128 | r + 1 < -127 | c + 1 > 128 | c + 1 < -127)
            point_west = 255;
        else
            point_west = double(I(r + 1 + 128, c + 1 + 128));
        end
        O_li(x_index + 128, y_index + 128) = (1-a)*(1-b)*point_north + a*(1-b)*point_east + b*(1-a)*point_south + a*b*point_west;
    end
end

% Display and title output.
colormap('gray');
subplot (1,3,1);
imagesc (I);
title('Original');
subplot (1,3,2);
imagesc (O_nni);
title('Nearest Neighborhood')
subplot (1,3,3);    
imagesc (O_li);   
title('Linear');