%image_file = 'AFGRL-10001C_best_12x16_tweaked4MacWorkflow_0.jpg';
image_file = 'lincoln-portrait.jpg';
TITLE_FONTSIZE = 12;

I = imread(image_file);

% if necessary, convert to grayscale
if (length(size(I)) > 2),
    I = rgb2gray(I);
end;

% if too large, scale
if (max(size(I)) > 512),
    I = imresize(I, 512/max(size(I)));
end;

%figure;
%imshow(I);
%title('original image', 'FontSize', TITLE_FONTSIZE);

% experimenting several values for the bilateral filter parameters

R = 10;
sigma_val = [.5 10];

for i = 1:length(sigma_val), % sigma_col
    for j = 1:length(sigma_val), % sigma_sp
        sigma_col = sigma_val(i);
        sigma_sp = sigma_val(j);
        
        X = I;
        [Y G] = bilateral(X, R, sigma_col, sigma_sp);
        Y = uint8(Y);
        YG = uint8(imfilter(double(I), G/sum(G(:))));

        figure;
        subplot(1,3,1);
        imshow(I);
        title('Original image', 'FontSize', TITLE_FONTSIZE);
        subplot(1,3,2);
        imshow(YG);
        title(['Gaussian filtered (R = ' num2str(R) ', \sigma_s = ' num2str(sigma_sp) ')'] , 'FontSize', TITLE_FONTSIZE);
        subplot(1,3,3); 
        imshow(Y);
        title(['Bilateral filtered (R = ' num2str(R) ', \sigma_s = ' num2str(sigma_sp) ', \sigma_i = ' num2str(sigma_col) ')'], 'FontSize', TITLE_FONTSIZE);
    end;
end;

%return

num_runs = 6;
sigma_col = 10;
sigma_sp = 5;

X = I;
YG = I;
for i = 1:num_runs,
    [Y G] = bilateral(X, R, sigma_col, sigma_sp);

    Y = uint8(Y);
    YG = uint8(imfilter(double(YG), G/sum(G(:))));
    
    if (0),
        figure;
        subplot(1,3,1);
        imshow(I);
        title('original image', 'FontSize', TITLE_FONTSIZE);
        subplot(1,3,2);
        imshow(YG);
        title('Gaussian filtered', 'FontSize', TITLE_FONTSIZE);
        subplot(1,3,3);
        imshow(Y);
        title('Bilateral filtered', 'FontSize', TITLE_FONTSIZE);
    end;
    X = Y;
end;

figure;
subplot(1,3,1);
imshow(I);
title('original image', 'FontSize', TITLE_FONTSIZE);
subplot(1,3,2);
imshow(YG);
title(['Gaussian filtered (#iter = ' int2str(num_runs) ', R = ' num2str(R) ', \sigma_s = ' num2str(sigma_sp) ')'], 'FontSize', TITLE_FONTSIZE);
subplot(1,3,3);
imshow(Y);
title(['Bilateral filtered (#iter = ' int2str(num_runs) ', R = ' num2str(R) ', \sigma_s = ' num2str(sigma_sp) ', \sigma_i = ' num2str(sigma_col) ')'], 'FontSize', TITLE_FONTSIZE);
        


