% Joe Jupin
% Homework 10
% plane image

%  clear all variables
clear all;

% color constants
red = 1;
green = 2;
blue = 3;

%  read image
f = imread('plane1.jpg');
% show unprocessed image
subplot(2,4,1);
imshow(f);

% get size of image
[xsize ysize zsize] = size(f);

% make boolean container
b = boolean(zeros(xsize, ysize));

% find all pixels with red values > 105
for i=1:xsize
    for j=1:ysize
        if f(i,j,red) > 105
            b(i,j) = 1;
        end
    end
end

% show boolean image
subplot(2,4,2);
imshow(b);



% neighborhood size
% must be an odd number
neigh = 11;
% padded boader size
bdr = (neigh-1)/2;
% make dilation container
bd = b;
% make erosion container
be = b;

% perform closing filter

% create zero padded image
bp = zeros(xsize+2*bdr, ysize+2*bdr);
bp(1+bdr:xsize+bdr, 1+bdr:ysize+bdr) = b;

% perform dilation filter
for i=1:xsize
    for j=1:ysize
        x = bp(i:i+2*bdr, j:j+2*bdr);
        bd(i, j) = max(max(x));
    end
end

% show dilation
subplot(2,4,3);
imshow(bd);

% re-pad image
bp = zeros(xsize+2*bdr, ysize+2*bdr);
bp(1+bdr:xsize+bdr, 1+bdr:ysize+bdr) = bd;

% perform erosion filter
for i=1:xsize
    for j=1:ysize
        x = bp(i:i+2*bdr, j:j+2*bdr);
        be(i, j) = min(min(x));
    end
end

% show erosion
subplot(2,4,4);
imshow(be);

% neighborhood size
% must be an odd number
neigh = 7;
% padded boader size
bdr = (neigh-1)/2;

% perform opening filter

% re-pad image
bp = zeros(xsize+2*bdr, ysize+2*bdr);
bp(1+bdr:xsize+bdr, 1+bdr:ysize+bdr) = be;

% perform erosion filter
for i=1:xsize
    for j=1:ysize
        x = bp(i:i+2*bdr, j:j+2*bdr);
        be(i, j) = min(min(x));
    end
end

% show erosion
subplot(2,4,5);
imshow(be);

% re-pad image
bp = zeros(xsize+2*bdr, ysize+2*bdr);
bp(1+bdr:xsize+bdr, 1+bdr:ysize+bdr) = be;

% perform dilation filter
for i=1:xsize
    for j=1:ysize
        x = bp(i:i+2*bdr, j:j+2*bdr);
        bd(i, j) = max(max(x));
    end
end

% show dilation
subplot(2,4,6);
imshow(bd);

% get boundaries
bbc = boundaries(bd);
bbd = bbc{1};

% make boolean boundary image
bb = boolean(zeros(xsize, ysize));
for i=1:length(bbd)
    bb(bbd(i,1), bbd(i,2)) = 1;
end

% show boundary image
subplot(2,4,7);
imshow(bb);

% make image trace container
fb = f;

% make image boundary image
for i=1:length(bbd)
    fb(bbd(i,1), bbd(i,2), 1) = 255;
    fb(bbd(i,1), bbd(i,2), 2) = 255;
    fb(bbd(i,1), bbd(i,2), 3) = 255;
end

% show boundary image
subplot(2,4,8);
imshow(fb);