% morph
%
%  Takes a descriptive file which is generated by calling track_positions.m and
%  morphs images as described in that file.
%
%  Bradley C. Grimm 
%  CS 6640 - Image Processing
%  October 29, 2009

function morph( param_filename )

% Load parameters file.
[control_x control_y input output_name steps kw] = load_params( param_filename, 0 );

% Find the values of the weights.
[N M] = size( control_x ); % Number of control points

% Determine our palette size.
images = [];
maxSz = [0 0 0];
for m=1:M
    Isz = size( imread( input(m,:) ) );
    if ( length(Isz) < 3 )
        Isz = [Isz 0];
    end
    maxSz = max(Isz, maxSz);
end

% Load in images, pad with zeros.
for m=1:M
    image = imread( input(m,:) );
    sz = size( image );
    if ( length(sz) < 3 )
        sz = [sz 0];
    end
    Isz = maxSz - sz;
    images(:,:,:,m) = padarray(image, [max(Isz(1), 0) max(Isz(2), 0)], 'post');
end

[height width channel num] = size(images);

% Scale down to 0.0 - 1.0 range
control_y = control_y / height;
control_x = control_x / width;

% Create an interpolated x and y
step = 1/(steps + 1);

% Compare each of the images with all others.
tic;
for n=1:num
    for m=n+1:num
        y1 = control_y(:,n);
        x1 = control_x(:,n);

        y2 = control_y(:,m);
        x2 = control_x(:,m);
        t=0.5
        for t=step:step:0.99
			% Interpolate control points.
            yt = (1 - t) * y1 + t * y2;
            xt = (1 - t) * x1 + t * x2;

            kernel = @thin_plate_spline;
            %kernel = @(s) ( exp( -kw * (s * s) ) );

			% Calculate weights
            k1 = calculate_rbf_weights( yt, xt, y1, x1, kernel );
            k2 = calculate_rbf_weights( yt, xt, y2, x2, kernel );

			% Generate new morphed images
            [dh dw c] = size( images(:,:,:,n) );
            I1 = interpolate_morph( yt, xt, k1, kernel, images(:,:,:,n), dh, dw );

            [dh dw c] = size( images(:,:,:,m) );
            I2 = interpolate_morph( yt, xt, k2, kernel, images(:,:,:,m), dh, dw );

			% Interpolate images and write.
            If = (1 - t) * I1 + t * I2;

            str = sprintf('%d_%d_%s_%f.png', n, m, output_name, t);
            imwrite(If, str, 'png');
        end
    end
end
toc
end

