%Need version 9
%Experimenting with matlab and lab pictures

close all

%read image
rgb = imread('000200 (teleconverter).jpg');


% open color thesholder app
colorThresholder(rgb)


%fill in holes
bw = imfill(BW2,'holes');
imshow(bw)


hold on

%outline
[B,L] = bwboundaries(bw, 'noholes');
% figure, imshow(bw); 
for k = 1:length(B)
    boundary = B{k};
    plot(boundary(:,2), boundary(:,1), 'r', 'LineWidth', 2)
end

%number the particles
s = regionprops(L, 'centroid');
centroids = cat(1, s.Centroid)

for K=1: length(centroids)
    x=centroids(K,1);
    y=centroids(K,2);
    a=num2str(K);
    text(x,y,sprintf('%d',K),'color','g','Fontsize',12)

end

hold off


%find the areas and perimeters of the objects detected in pixels
D1 = regionprops(bw, 'area'); 
D2 = regionprops (bw, 'perimeter');
%answers in structure array form
%will sometimes say perimeter=0 because can't measure when outer pixels don't
%directly connect on image

%converting from structure array to matrix form
areatemp = cell2mat(struct2cell(D1)) ;
perimtemp = cell2mat(struct2cell(D2)) ;

%finding areas of particles in mm^2 and microns^2
area_mm = (areatemp/12715381410)*1e6; %pixels to mm^2
area_microns = (areatemp/12715381410)*1e12; % pixels to microns^2

%finding perimeter of particles in mm and microns
perim_mm = (perimtemp/112762.5)*1e3; %pixels to mm
perim_microns = (perimtemp/112762.5)*1e6; %pixels to microns

%finding radii assuming particles are perfect circles
radius_mm = ((area_mm)/pi).^(1/2);
radius_microns = ((area_microns)/pi).^(1/2);

%finding diameter assuming particles are perfect circles
diameter_mm = radius_mm.*2;
diameter_microns = radius_microns.*2;

%sort diameter in ascending order
ascending_diameter_microns = sort(diameter_microns);

%bar graph
figure
bar (ascending_diameter_microns);
grid on
title('Sizes of Detected Particles')
ylabel('Diameter of Particle if Perfect Circle (um)') % y-axis label

