%Imari Walker Karega
%Dec 1, 2015
%Final Project
%In order to run this script all 153 images from march would be needed

clear all
%clc
%cd('Thesis');
cd('NH1304_March2013_CFE');
cd('PL2FLAT');

directory = dir('*.bmp');
n = numel(directory);

%set up intial conditions

height = 1900;
width = 1800;
radius = 942;
H = 1000;
w = 980;
A = zeros(height,width);
%8 pixels are needed to connect to be a particle
conn = 8;
f = 0;
r_old = 0;
for i = 1:n
    files = directory(i).name;
    im = imread(files);
    [rows, columns, numberOfColorChannels] = size(im);
    if numberOfColorChannels > 1
        Igray = rgb2gray(im);
    else
        Igray = im; % It's already gray.
    end
    
    %this establishes what is considered a particle or not
    % if there are values greater than 3 then it is marked as a 1
    %this is a way of thresholding each item the same way
    
    for k = 1:height
        for j = 1: width
            rt = sqrt((k-H)^2+((j-w)^2));
            if rt > radius
                Igray(k,j) = 0;
            end
            if Igray(k,j) < 3
                A(k,j) = 0;
            elseif Igray(k,j) >= 3
                A(k,j) = 1;
            end
            
        end
    end
    %convert to black white image then finds the area of particles
    BW = im2bw(A);
    area(i) = bwarea(BW);
    connected = bwconncomp(BW, conn);
    Label = bwlabeln(BW,conn);
    %determine the number of particles
    r(i) = [connected.NumObjects];
    
    figure(1);
    FigHandle = gcf;
    fig.PaperUnits = 'inches';
    fig.PaperPosition = [0 0 9 3];
    %set(FigHandle, 'Position', [100, 100, 049, 895]);
    %plot images in subplot
    subplot(1,2,1), imshow(BW);
    title('Carbon Flux Explorer Image');
    
    %plot the depth vs number of particles connected by 8 pixel
    subplot(2,2,2),
    %plot([i i-1],[r_old r],'o-') %'-g');
    plot(i,r(i),'o-') %'-g');
    xlabel('Change in Time');
    ylabel('Number of Particles');
    xlim([1 155])
    ylim([0 6000])
    hold on
    drawnow
    
    %plot time vs area of particles
    subplot(2,2,4),plot(i,area(i),'o');
    xlabel('Change in Time');
    ylabel('Area of Particles');
    axis tight
    xlim([1 155])
    hold on
    %pause
    r_old = r;
    % %saving the images to print
    if i==n
        subplot(2,1,1), 
        plot(1:i-1,area(1:i-1))
        title('Final Plot of Particle Area for each Image')
        xlabel('Image Number');
        ylabel('Area of Particles');
        xlim([1 155])
        subplot(2,1,2),plot(1:i-1,r_old(1:i-1),'o-') %'-g');
        title('Final Plot of Number of Particles for each Image')
        xlabel('Image Number');
        ylabel('Number of Particles');
        xlim([1 155])
%        
    end
    
    fname = ['CFE_',sprintf('%03d',f),'.png'];
    print(fname,'-r300','-dpng')
    disp(['saving image' num2str(i)])
    f=f+1;
end

March = table([1:i-1]',area(1:i-1)');