function C = AddImage(A,B,c,tol)
% A is an mA-by-nA-by-3 uint8 color array that corresponds to an image IA
% B is an mB-by-nB-by-3 uint8 color array that corresponds to an image IB
% C is an mA-by-nA-by-3 uint8 color array that corresponds to a
% superpositioning of IB on IA. The location of the superpositioning is
% solicited via ginput. A Source pixel in B is copied to its Target pixel
% in A only if colorDist(c,v)>=tol where v is the rgb vector associated
% with the pixel.

close all
[mA,nA,z] = size(A);
[mB,nB,z] = size(B);

imshow(A)
[x,y] = ginput(1);
i0 = floor(y)
j0 = floor(x)

for iB=1:mB
for jB=1:nB
% Pixel (iB,jB) in B is mapped to pixel(iA,jA) in A
iA = i0+iB-1;
jA = j0+jB-1;
% The rgb vector for B(iB,jB)..
v = double([B(iB,jB,1) B(iB,jB,2) B(iB,jB,3)])/255;

if 1<=iA && iA<=mA && 1<=jA && jA<=nA && colorDist(v,c)>tol
A(iA,jA,1) = B(iB,jB,1);
A(iA,jA,2) = B(iB,jB,2);
A(iA,jA,3) = B(iB,jB,3);
end
end
end
C = A;

function alfa = colorDist(c1,c2)
alfa = abs(c1(1)-c2(1)) + abs(c1(2)-c2(2)) + abs(c1(3)-c2(3));