[X,MAP] = imread('StarWars.png');
imwrite(X,MAP,'StarWars.jpg','jpg');
sw = imread('StarWars.jpg');
figure; imshow(sw)

b = im2bw(sw, 0.9);
figure; imshow(b)

bi = ~b;
figure; imshow(bi)

a= imread('A.png');
figure; imshow(a)
a1 = im2bw(a, 0.5);
se = ~a1;
figure; imshow(se)

Apos= imerode(bi, se);
figure; imshow(Apos)

OnlyAs = imdilate(Apos, se);
figure; imshow(OnlyAs)


% Create a color image with red 'a' letters
color = sw;

% extract the red, green and blue channels
R = color(:, :, 1);
G = color(:, :, 2);
B = color(:, :, 3);

pos=find(OnlyAs==1); % find the positions of all white pixels

R(pos)= 255;  % set the corresponding pixels in red
G(pos)= 0;    % clear the green channel
B(pos)= 0;    % clear the blue channel

% combine the modified three channels to get the desired image
color(:, :, 1) = R;
color(:, :, 2) = G;
color(:, :, 3) = B;

figure; imshow(color)


% Or you can use this shortcut
colorAs = imoverlay(sw, OnlyAs, [1, 0, 0]);
figure; imshow(colorAs)





% Replace the A's with C's
c = imread('C.png');
figure; imshow(c)
c1 = im2bw(c, 0.5);
se2 = ~c1;
figure; imshow(se2)

OnlyCs = imdilate(Apos, se2);
figure; imshow(OnlyCs)

% first attempt:  this draws red C's over the A's
colorCs = imoverlay(sw, OnlyCs, [1, 0, 0]);
figure; imshow(colorCs)

% second attempt: erase the A's befroe drawing the C's
colorCs = imoverlay(sw, OnlyAs, [1, 1, 1]);
colorCs = imoverlay(colorCs, OnlyCs, [1, 0, 0]);
figure; imshow(colorCs)

% third attempt: dilate the A's and then do the same as in the second attempt
OnlyAs2 = imdilate(OnlyAs, ones(3,3));
colorCs = imoverlay(sw, OnlyAs2, [1, 1, 1]);
colorCs = imoverlay(colorCs, OnlyCs, [1, 0, 0]);
figure; imshow(colorCs)
