%function cell_classify(filename);

%Input = name of file containing input binary image (text string) 
%Output = Writes out a tif file "output.tif" containing the image with cells classified

atresh = 500;   %threshold for "area of small cells"
threshold = 1;  %threshold for rho/(4*pi)

%filename = 'blood.tif';
filename = input('Enter file name\n','s');

%Read input binary image
a = imread(filename);
a = ~a;
%max(a(:))
%min(a(:))
[height,width] = size(a);
imshow(a);
%pause

%create border of ones
b = ones(height+2,width+2);
b(2:height+1,2:width+1) = a;
a = b;
clear b;

%find 8-connected components of input image
[b,ncomp] = bwlabel(a,8);
%type is the type of each connected component
type = zeros(ncomp,1);
type(b(1,1)) = 0;

%eliminate "border" connected component
temp = b(1,1);
b = b.*((b-temp) ~= 0);
%figure
%imshow(b,[]);
%pause

%remove the border that was appended previously
b = b(2:height+1,2:width+1);

%figure
%imshow(b,[]);
%pause

%classify each connected component
for k = 1:ncomp
   
   %isolate the component
   c = ((b - k) == 0);
   %imshow(c,[]);
	%pause

   %if area of component < atresh, eliminate it
   if(sum(c(:)) < atresh) 
      type(k) = 0;
      b = b.*(~c);
   %else, retain it and check if it has hole(s) in it
   else
      c = ~c;
   	c = uint8(c);
   	[d,m] = bwlabel(c,8);
      
      if(m == 2)  %component has one hole 
      
      	d = bwfill(~c,'holes');
         e = bwperim(d);
         
         %imshow(~c,[])
      	%pause
      	%imshow(d,[])
      	%pause
      	%imshow(e)
      	%pause

      	perimeter = sum(e(:));
      	area = sum(d(:));
      	ratio = perimeter*perimeter/(4*pi*area);
      	if(ratio < threshold) 
         	type(k) = 1;   %normal cell
      	else
         	type(k) = 3; %unknown type
      	end
      
   	elseif(m > 2) %component has more than one hole
      
     	 	d = bwfill(~c,'holes');
     	 	e = bwperim(d);
      	perimeter = sum(e(:));
      	area = sum(d(:));
      	ratio = perimeter*perimeter/(4*pi*area);
      	if(ratio > threshold) 
         	type(k) = 2;   %overlapping cells
      	else
         	type(k) = 3;     %unknown type
      	end
   	else
      	type(k) = 3;     %unknown type   
      end
   end
end

%background component has not been assigned any type
%so just assign it type 0, which will map to grayvalue 0
type = [0;type];

%assign different grayvalues to the three cell types
test = 100 + 50*type(b+1);
test = test.*(b ~= 0);

%display output and write it to file
figure(2)
imshow(test,[]);
test = uint8(test);
imwrite(test,'output.tif');

