%This script allows a step-by step segmentation of the nuclei


clear

hold off

close all

%FIRST IMPORTANT THING TO CHANGE: USE THE RIGHT PATH FOR THE SEGMENTATION
%ROUTINES AND THE OUTPUT

path_routines='C:\Science\To Submit\Segmentation Routines'; %Where your quantification routines are
pathOutput=pwd;


%SECOND IMPORTANT THING TO CHANGE: USE THE RIGHT PATH FOR THE NAME OF THE
%.TIF FILE TO BE ANALYZED AND WHERE TO FIND IT.

fileNameTrack='Example.tif'
pathInputTrack='C:\Science\To Submit\Example Segmentation Tracking\'

filenamesave=strcat('Segment',strrep(fileNameTrack,'.tif','.mat'));

cd(path_routines)
[StackTrack, nFrames] = TIFread([pathInputTrack, fileNameTrack]);
cd(pathOutput); 


%parameters of the first segmentation 

sigmaquant=0.1; %For the first approximate segmentation of objects
sizemin=50; %Minimum size (area) of the objects to be selected
factor_roughthres=0.2; %A factor to be used for the thresholding of approximate objects
factor_finethres=0.8; %A factor to be used for the fine threshold of the objects as factor*mean value of a window containing the objects
sizemax=10000; %Maximum size (area) of the objects to be selected
printornot='YES'; %Allows to visualize the sementation, write NO otherwise


parCellSeg= [sigmaquant sizemin factor_roughthres factor_finethres sizemax]

cd(path_routines)
[cellROIs]=SegmentShinyObjects(StackTrack, parCellSeg, printornot)
cd(pathOutput); 


%%Second segmentation of big objects: the bigger value selected is 300

minsize=70;
maxsize=300;


cd(path_routines)
for n=1:nFrames
    
    [cellroisframe] = functionOneRoundWSBigObjects(cellROIs(n),minsize,maxsize);    
    cellROIsdef(n)=cellroisframe;
    baricenters = regionprops(cellroisframe,'Centroid');
    baricenters = cell2mat((struct2cell(baricenters))');
    points{n}=baricenters;
 
%     figure(3)
%     imagesc(StackTrack(n).data,[1 70000])
%     hold on;
%     plot(baricenters(:,1), baricenters(:,2), 'w+');
% Uncomment the previous one in case you want to see who the segmentation
% proceeds
    
end;
cd(pathOutput); 


save(filenamesave,'cellROIsdef','points');











