%% Quanli Wang
% This example demostrates applying MCF Size Transform to BBBC
% drosophila_kc167_1 benchmark image set for cell counting
% more details on data and bench mark can be found at 
% http://www.broadinstitute.org/bbbc/drosophila_kc167_1.html

addpath dist

%% read in the data
[name c1 c2]  = textread('images\drosophila_kc167_1_counts.txt', '%s %d %d');

%% method 1:
%parameters:
disk = 5; pixelminmax = 20; maxcellsize = 5000;

% segmentaion image and cell count are saved in result3 and resultcount
resultcount = []; 
for i = 1:length(c1)
    b = imread(['images/kc167/' name{i} '.TIF']);
    figure(1),imshow(b,[])
    
    %smoothing
    [X3 A3] = ImmersionSimulation1(255-b, @ISSO_SizeShapeFilter, @ISSO_agr,[3 * disk*disk maxcellsize disk 1], []);
    figure(2),imshow(A3>0,[])
    result1{i} = A3;
    
    %find the size of the largest object
    temp = ApplyToEach(double(A3),0,4, {@(x) (x>0)*length(x(x>0))},{});
    
    %Rank Transform and thresholding using default values
    mask = A3 > 0;
    r = eblock(A3,[],mask,ceil(sqrt(max(temp(:)))),{@ranks},{1});
    figure(15),imshow(r>0.5,[])
    result2{i} = r;
    
    %%MCF binary segmentation using default settings
    r = BinarySeg(r>0.5,10);
    r = bwareaopen(r,3 * (disk-1) * (disk-1)); %watershed lines are not counted
    
    %%remove objects that is way to dim
    b(r==0) = 0; temp = ApplyToEach(double(b),0,4, {@(x) (x>0)*max(x(:))},{}); r(temp < pixelminmax) = 0;
    [L num] = bwlabel(r); [i num c1(i) c2(i)]
        
    result3{i} = r;
    resultcount = [resultcount num];
            
    rgb = label2rgb(L,'jet','k', 'shuffle');
    figure(8),imshow(rgb)
    
end
