
% This script demonstrates how a modulation of a Laplacian membrane is used for adjusting color
% while performing seamless cloning.
% The membrane is computed using "Convolution Pyramids" [Farbman et al. 2011].
% Some of the alpha masks were created manually, while other we have used "Improving Image Matting using Comprehensive Sampling Sets" [Shahrian 2013].
% For automatically computing W, we have used "Improving Perceptual Color Difference using Basic Color Terms" [Pele and Werman 2002].
% Our method takes the following images: source image, target image, binary mask (used for cloning), alpha mask (used to identify foreground region), the Laplacian membrane, and the value of the parameter w
%   For more details: 
%   http://www.inf.ufrgs.br/bhenz/projects/color_adjustment


close all
clear all
clc
addpath(genpath('./conv_pyr'));


%% Load files

folder = 'images/portrait';
src = im2double(imread(strcat(folder,'/source.jpg')));
trg = im2double(imread(strcat(folder,'/target.jpg')));
alpha = im2double(imread(strcat(folder,'/alpha.png')));
alpha = alpha(:,:,1);
alpha3channel = cat(3,alpha,alpha,alpha);

if exist(strcat(folder,'/mask.png'))
    mask = im2double(imread(strcat(folder,'/mask.png')));
    mask = logical(mask(:,:,1));
else
    mask = imdilate(logical(alpha),strel('disk',2));    
end

%% Alpha blending
blending = trg;
res_blend = zeros(size(trg));
res_blend(:,:,:) = alpha3channel .* src(:,:,:) + (1-alpha3channel) .* trg(:,:,:);
figure(); imshow(res_blend); title('Alpha Blending');

%% Seamless Cloning - Convolution Pyramid
tic;
[res_poisson,membrane] = ConvolutionPyramid(src, trg, mask);
figure(); imshow(res_poisson); title('Poisson Cloning');
elapsedTimeMembrane = toc;

%% Color Correction
tic;
automaticW = computeW(src,trg,mask,alpha);
elapsedTimeW = toc;
tic;
res_automatic_w = ColorCorrection(src, trg, mask, alpha, membrane,automaticW);
elapsedTimeCorrection = toc;

%% Different parameters
parameters = [automaticW .65 .7 .75 .8 .85 ];

for i=1:length(parameters)
    results{i} = ColorCorrection(src, trg, mask, alpha, membrane, parameters(i));
end


figure;
subplot(2,3,1);
imshow(results{1}); title(strcat('Automatic w = ',num2str(parameters(1))));
for i=2:length(parameters)
subplot(2,3,i);
imshow(results{i}); title(num2str(parameters(i)));
end



