%% Quanli Wang, Mike West
% quanli@stat.duke.edu
% MCF Size Transform Example for Speckle Counting
addpath dist

%read input images
a = imread('images\1-162hrhoe2.tif');
data{1} = uint8(mat2gray(a)*255);
a = imread('images\1-162hrh2ax2.tif');
data{2} = uint8(mat2gray(a)*255);
figure(1),imshow(data{1},[])
figure(2),imshow(data{2},[])

% Size transform parameters
[m n] = size(data{1});
minsize = floor(m * n * 0.1);
maxsize = floor(m * n * 0.9); 


%% MCF size transform
i = 1;    %for cell detection
    % image reconstruction using size transform
    [x1 f1] = ImmersionSimulation1(data{i}, @ISSO_SizeShapeFilter, @ISSO_agr,[minsize maxsize], []);    
    figure(3),imshow(imcomplement(f1),[]); title('reconstructed image using size transform');
    
    % simple global thresholding for cell detection
    level = graythresh(f1);
    mask = 1-im2bw(f1,level);
    figure(4),imshow(mask); title('cell detection');
    
    % cell segmentation using MCF binary segmentor 
    cells = BinarySeg(mask,5000);
    [L num] = bwlabel(cells);
    figure(5),imshow(label2rgb(L),[]); 
    
    
 i = 2;     % for speckle detection
    sp = imcomplement(data{i});
    sp(cells==0) = max(sp(:)); 
    figure(6),imshow(sp,[]);
    
    %parameters used for speckle counting
    minarea = 10;maxarea = 100;disk = 1;thresh = 5;
    A = ISSO_Speckle(sp,disk,minarea,maxarea,thresh);
    figure(7),imshow(log(double(A+1)),[]) 
   
 %% output images for the paper
%  imwrite(data{1},'cp_nuclei.tif');
%  imwrite(data{2},'cp_foci.tif');
%  temp = uint8(mat2gray(imcomplement(f1))*255);
%  imwrite(temp,'cp_enhanced.tif');
%  temp =label2rgb(L);
%  imwrite(temp,'cp_segmented.tif');
%  imwrite(mask,'cp_segemnted1.tif');
%  temp = log(double(A+1));
%  temp1 = temp(180:450,700:950);
%  temp1 = temp1 >0;
%  figure(10),imshow(temp1);
%  imwrite(temp1,'cp_foci_segmented.tif');
%  
%  temp  = data{2};
%  temp1 = temp(180:450,700:950);
%  figure(10),imshow(temp1);
%  
%  temp = imread('a.png');
%  figure(10),imshow(temp,[])
%  temp1 = temp(168:295,435:551,:);
%  figure(101),imshow(temp1,[])
%  imwrite(temp1,'cp_foci_cp.tif');
 
 