input = imread('a1_input.jpg');
input_size = size(input);
height = floor(input_size(1)/3);
width = input_size(2);

B = input(1:height,:);
G = input(height+1:2*height,:);
R = input(2*height+1:3*height,:);

range = 15;
margin = 20;


R = double(R);
G = double(G);
B = double(B);

template = R(margin+1:height-margin,margin+1:width-margin);

error_G = zeros(2*range+1,2*range+1);
temp_G = zeros(height-2*margin,width-2*margin);
for x=-range:range
    for y=-range:range
        temp_G(1:height-2*margin,1:width-2*margin) = G(margin+1+x:height-margin+x,margin+1+y:width-margin+y);
        error_G(range+1+x,range+1+y)=sum(sum((template-temp_G).^2));
    end
end

error_B = zeros(2*range+1,2*range+1);
temp_B = zeros(height-2*margin,width-2*margin);
for x=-range:range
    for y=-range:range
        temp_B(1:height-2*margin,1:width-2*margin) = B(margin+1+x:height-margin+x,margin+1+y:width-margin+y);
        error_B(range+1+x,range+1+y)=sum(sum((template-temp_B).^2));
    end
end

[row_G,col_G] = find(error_G == min(error_G(:)));
[row_B,col_B] = find(error_B == min(error_B(:)));

output = zeros(height-2*margin,width-2*margin,3);
output(:,:,1) = R(margin+1:height-margin,margin+1:width-margin);
output(:,:,2) = G(margin+1+row_G-range-1:height-margin+row_G-range-1,margin+1+col_G-range-1:width-margin+col_G-range-1);
output(:,:,3) = B(margin+1+row_B-range-1:height-margin+row_B-range-1,margin+1+col_B-range-1:width-margin+col_B-range-1);
output=uint8(output);
imshow(output);

    

