ls_detect_chromosomes.m 13.5 KB
Newer Older
M. Julius Hossain's avatar
M. Julius Hossain committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322
function [procStat] = ls_detect_chromosomes(curInDir, curOutDir, segParamsDir, exParamsFn, chrChanIdx, poiChanIdx, dispSegMass, nRemLowerSlices, inFileExt, cropFlag, cropDx, cropDy, saveChrMarker, chr_op, varargin)
% LS_DETECT_CHROMOSOMES
% This function segments chromosome from chrChan and save chromsome chrMarker for cell boundary detection
% curInDir: full path containing time lapse raw image stacks
% curOutDir: full path to output directory where to save chromosome markers
% chrChaIdx: Index of chromosome channel
% exParamsFn: Name of the file storing the extracted parameters.
% chrChanIdx: id/serial number of the channnel containg DNA image
% poiChanIdx: id/serial number of the channnel containg protein of interest
% dispSegMass: Flag to visual segmentation results
% nRemLowerSlices: number of lower slices to to be removed from analyis
% inFileExt: Extension raw input file (lsm/tif)
% cropFlag: Set 1 to crop, 0 otherwise
% cropDx: number of row in cropped image
% cropDy: number of column in cropped image

% Author: Julius Hossain, EMBL, Heidelberg, Germany: julius.hossain@embl.de
% Created: 2014-07-25
% Last update: 2019-01-08

close all;
procStat = 0; %Should go through the last part of the code to be set as 1
disp(['PROCESSING:' curInDir]);
lsmFn = dir([curInDir inFileExt]);

tMax = length(lsmFn); %Number of lsm file in the folder
if tMax == 0
    disp('Input file(s) missing');
    return;
end

if saveChrMarker == 1 && length(varargin)> 0
    curOutDirMarker = varargin{1};
end

if dispSegMass == 1
    dispDir = fullfile(curOutDir, 'DispSegMass', filesep);
    if ~exist(dispDir)
        mkdir(dispDir);
    end
end

tinit = 1;
%% Read bioformats header
[reader, dim] = getBioformatsReader([curInDir lsmFn(1).name]);

% Extract image dimensions
dx = dim.Ny; %Image height
dy = dim.Nx; % Image width
NzOrig = dim.Nz; %Number of Z slices in tif files
Nc = dim.Nc; %Number of channels


zinit = 1; %Set higher than one if you want to some of the lower slices
%Size of voxels in x, y and z in micro meter
voxelSizeX = dim.voxelSize(1);
voxelSizeY =  dim.voxelSize(2);
voxelSizeZ =  dim.voxelSize(3);

%% Update metadata for isotropic data that will be generated by interpolation
zFactor = round(voxelSizeZ/voxelSizeX); % zFactor-1 intermediate slice(s) will be generated
voxelSizeZ = voxelSizeZ/zFactor; % Update voxelSizeZ based on the number of intermediate slices
voxelSize = voxelSizeX * voxelSizeY * voxelSizeZ; %Volume of a voxel in cubic micro meter
Nz = (NzOrig-zinit+1) * zFactor - zFactor + 1; %Number of z slice after intepolation
chrStackOrig = zeros(dx,dy,NzOrig-zinit+1); % Allocate memomry for original stack

inHomCount = 0; % Defines the number of times we need to apply fn_InhomToHom(stk)
inHomCheck = 1; % Flag whether to check homogeinity or not

% Name of the parameters to save as marker
paramsName = {'ChrVolMic','NumChr', 'TotPoiInt', 'AvgPoiInt'};
paramsTable = cell2table(cell(1,length(paramsName)));
paramsTable.Properties.VariableNames = paramsName;

%Process all time points on by one
tpoint = tinit;
dataRead = 1;
while tpoint <=tMax
    if dataRead == 1
        %Read bioformat header
        [reader, dim] = getBioformatsReader([curInDir lsmFn(tpoint).name]);
        
        %Get raw stacks containing DNA and POI
        chrStackOrig = getTPointBioFormats(reader, dim, 1, chrChanIdx);
        poiStackOrig = getTPointBioFormats(reader, dim, 1, poiChanIdx);
        
        % Crop images if needed
        if cropFlag == 1
            chrStackOrig = fn_crop_stack(chrStackOrig, cropDx, cropDy, nRemLowerSlices+1);
            poiStackOrig = fn_crop_stack(poiStackOrig, cropDx, cropDy, nRemLowerSlices+1);
            [dx, dy, NzOrig] = size(chrStackOrig);
            Nz = (NzOrig-zinit+1) * zFactor - zFactor + 1; %Number of z slice after intepolation
        end
        
        %Interpolate the images for making it isotropic
        chrStack = ls_gen_intermediate_slices(chrStackOrig, zFactor);
        clear chrStackOrig;
        
        %Initializing varibales storing data for different stages
        if tpoint == tinit
            chrRegion = zeros(dx,dy,Nz);%Store the detected chromosome region
            chrRegionCur1 = zeros(dx,dy,Nz);
            chrRegionCur2 = zeros(dx,dy,Nz);
            chrRegionPrev1 = zeros(dx,dy,Nz);
            bordImg = zeros(dx,dy,Nz); % Used for marker based watershed
            bordImg(1,:,:) = 1; bordImg(end,:,:) = 1;
            bordImg(:,1,:) = 1; bordImg(:,end,:) = 1;
            imgCentX = (dx+1)/2;
            imgCentY = (dy+1)/2;
            chromosomes = zeros(dx,dy,Nz);
        end
        %Apply Gaussian filter
        chrStack = imgaussian(chrStack, chr_op.sigmaBlur, chr_op.hSizeBlur);
        dataRead = 0;
    end
    disp(['Detecting nuclear volume: ' lsmFn(tpoint).name]);
    % This part deals with inhomogeinity where intensity of chr of interest is dim
    for iter = 1:inHomCount
        chrStack = ls_inhomogeneous_to_homogeneous(chrStack);
    end
    
    %Get thresholds for individual sileces as well as entire stack
    [chrThresh3D, chrThresh2D] = ls_get_thresholds(chrStack);
    
    for i = 1:Nz
        chrRegion(:,:,i) = double(chrStack(:,:,i) >= (chrThresh3D * (1-chr_op.bFactor2D) + chrThresh2D(i) * chr_op.bFactor2D));
        chrRegion(:,:,i)=imfill(chrRegion(:,:,i),'holes');
    end
    
    % Detect connected component in the binarized image
    threeDLabel = bwconncomp(chrRegion,18);
    nCompI = threeDLabel.NumObjects;
    %disp(sprintf('Number of connected components is: %g', nCompI));
    
    %Check whether detected number of component is too high
    if inHomCheck == 1 && tpoint == tinit && nCompI >= chr_op.maxNoInitObj && inHomCount >=1
        inHomCount = inHomCount - 1;
        inHomCheck = 0;
        %Save the thresholds and number of components if needed to check
        fileID = fopen([segParamsDir lsmFn(tpoint).name(1:end-10) '_PAR.txt'],'a');
        fprintf(fileID,'%s %02d,   %s %05.f,   %s %04.f\n\r', 'tpoint:', tpoint, 'th3D:', chrThresh3D, 'nCompI:', nCompI);
        fclose(fileID);
        continue;
    end
    
    %Try to have higher threshold if number of detected compoents are very
    %hight
    if (inHomCheck == 0 || tpoint == tinit) && nCompI >= chr_op.maxNoInitObj
        [chrRegion, chrThresh3D, chrThresh2D, threeDLabel]= ls_adjust_thresholds_up(chrStack, chrThresh3D, chrThresh2D, chr_op.maxNoInitObj, chr_op.bFactor2D, threeDLabel);
    end
    
    nCompF = threeDLabel.NumObjects;
    numPixels = cellfun(@numel,threeDLabel.PixelIdxList);
    [initVol, idx] = max(numPixels);
    if threeDLabel.NumObjects > chr_op.maxNoInitObj * chr_op.nObjRatio %This is just to speed up the processing
        chrRegion(:,:,:) = 0;
        for i=1:min(round(chr_op.maxNoInitObj * chr_op.nObjRatio),threeDLabel.NumObjects)
            [~, idx] = max(numPixels);
            chrRegion(threeDLabel.PixelIdxList{idx}) = 1;
            numPixels(idx) = 0;
        end
    end
    
    %Get the volume of the largest component
    initVol = initVol * voxelSize;
    
    if inHomCheck == 1 && tpoint == tinit && initVol < 3*chr_op.mergeVol
        if inHomCount == 0
            fileID = fopen([segParamsDir lsmFn(tpoint).name(1:end-10) '_PAR.txt'],'w');
        else
            fileID = fopen([segParamsDir lsmFn(tpoint).name(1:end-10) '_PAR.txt'],'a');
        end
        fprintf(fileID,'%s %02d,   %s %05.f,   %s %04.f\n\r', 'tpoint:', tpoint, 'th3D:', chrThresh3D, 'initVol:', initVol);
        fclose(fileID);
        inHomCount = inHomCount + 1;
        continue;
    end
    
    %Split large connected components if needed
    chrMarker = ls_split_connected_chromosomes(chrRegion, voxelSizeX, voxelSizeY, voxelSizeZ, bordImg, chr_op.splitVol, chr_op.mergeVol);
    %displaySubplots(chrMarker, 'Chromosome - initial chrMarker after split', disRow, disCol, Nz, zFactor, 2);
    
    %Merge smaller connected component if needed
    chrMarker = ls_merge_small_regions(chrRegion, chrMarker, bordImg, voxelSizeX, voxelSizeY, voxelSizeZ, chr_op.mergeVol);
    %displaySubplots(chrMarker, 'chrMarker image - merged', disRow, disCol, Nz, zFactor, 2);
    
    %Remove tiny component if needed
    chrMarker = ls_remove_small_objects(chrMarker, 18, chr_op.mergeVol, bordImg, voxelSize);
    
    %% Recompute connected component
    threeDLabel = bwconncomp(chrMarker,18);
    numPixels = cellfun(@numel,threeDLabel.PixelIdxList);
    %Use location information to select the nucleus of interest
    stat = regionprops(threeDLabel,'Centroid');
    
    if tpoint == tinit
        %Detect nuclear volume from the first time point
        [chrRegionCur1, curCentX1, curCentY1, curCentZ1] = ls_detect_chromosome_in_first_stack(threeDLabel, stat, imgCentX, imgCentY, numPixels, dx, dy, Nz);
        
        %Get distance from the center of the image
        distCent = sqrt((imgCentX-curCentX1)^2 + (imgCentY-curCentY1)^2) * voxelSizeX;
        ncVolume1 = sum(sum(sum(chrRegionCur1))) * voxelSize;
        %disp(sprintf('distCent = %g', distCent));
        
        if inHomCount == 0 && inHomCheck == 1
            fileID = fopen([segParamsDir lsmFn(tpoint).name(1:end-10) '_PAR.txt'],'w');
        else
            fileID = fopen([segParamsDir lsmFn(tpoint).name(1:end-10) '_PAR.txt'],'a');
        end
        fprintf(fileID,'%s %02d,   %s %05.f,   %s %04.f   %s %04.f   %s %04.f\n\r', 'tpoint:', tpoint, 'th3D:', chrThresh3D, 'volChr: ', ncVolume1, 'nCompI: ', nCompI, 'nCompF: ', nCompF);
        fclose(fileID);
        
        %If homogenity check is on look at the volume of the first detected
        %connected component
        if inHomCheck == 1
            if ncVolume1 > chr_op.minProphaseVol * 2 && inHomCount >= 1
                inHomCount = inHomCount - 1;
                inHomCheck = 0;
                continue;
            elseif distCent > chr_op.maxCentDisp || ncVolume1 < chr_op.minProphaseVol
                inHomCount = inHomCount + 1;
                continue;
            else
                inHomCheck = 0;
            end
        end
        
        numChr = 1;
    else
        %Detect nuclear volume from the first time point
        if numChr == 1
            prevCentX2 = prevCentX1;
            prevCentY2 = prevCentY1;
        end
        [chrRegionCur1, chrRegionCur2, curCentX1, curCentY1, curCentZ1, curCentX2, curCentY2, curCentZ2, numChr] = ls_detect_chromosome_in_later_stacks(threeDLabel, stat, chrRegionPrev1, prevCentX1, prevCentY1, prevCentX2, prevCentY2, numPixels, numChr, voxelSizeX, voxelSizeY, voxelSizeZ);
        
        ncVolume1 = sum(sum(sum(chrRegionCur1)))*voxelSize;
        ncVolume2 = sum(sum(sum(chrRegionCur2)))*voxelSize;
        fileID = fopen([segParamsDir lsmFn(tpoint).name(1:end-10) '_PAR.txt'],'a');
        fprintf(fileID,'%s %02d,   %s %05.f,   %s %04.f   %s %04.f   %s %04.f\n\r', 'tpoint:', tpoint, 'th3D:', chrThresh3D, 'volChr: ', ncVolume1+ncVolume2, 'nCompI: ', nCompI, 'nCompF: ', nCompF);
        fclose(fileID);
    end
    
    prevCentX1 = curCentX1;
    prevCentY1 = curCentY1;
    %prevCentZ1 = curCentZ1; %This parameters is not used
    
    chrRegionPrev1 = chrRegionCur1;
    
    if numChr == 2
        prevCentX2 = curCentX2;
        prevCentY2 = curCentY2;
        %prevCentZ2 = curCentZ2;
        %chrRegionPrev2 = chrRegionCur2;
    end
    
    % Assign detected nucleus of interest - use two label after segregation
    chromosomes(:,:,:) = 0;
    chromosomes(chrRegionCur1(:,:,:) == 1) = 1;
    chromosomes(chrRegionCur2(:,:,:) == 1) = 2;
    
    %Get volume to stor in the mat file
    chrVolMic  = sum(sum(sum(chromosomes(:,:,:)>0))) * voxelSize;
    savefile = [curOutDir lsmFn(tpoint).name(1:end-4) '.mat'];
    chrMass = ls_remove_intermediate_slices(chromosomes, zFactor);
    
    poiIntStack = poiStackOrig;
    poiIntStack(chrMass ==0) = 0;
    totInt = sum(sum(sum(poiIntStack)));
    totNumVox = sum(sum(sum(chrMass >0)));
    avgPoiInt = totInt/totNumVox;
    save(savefile, 'chrMass', 'chrVolMic', 'numChr', 'totInt', 'avgPoiInt'); %Set 1 and 2 for first and second chromosome masses, res.
    
    newTable = cell2table({chrVolMic,numChr, totInt, avgPoiInt});
    newTable.Properties.VariableNames = paramsName;
    paramsTable = cat(1,paramsTable,newTable);
    
    
    if saveChrMarker == 1
        savefile = [curOutDirMarker lsmFn(tpoint).name(1:end-4) '.mat'];
        save(savefile, 'chrMarker', 'chromosomes', 'numChr', 'chrThresh3D', 'chrThresh2D');
    end
    
    %% Visulize detected nuclear volume
    % 8 corner points are set to 1 in order to keep effective volume same in all timepoints
    if dispSegMass == 1
        chrRegionCur1(1,1,1) = 1;     chrRegionCur1(1,1,end) = 1; chrRegionCur1(1,end,1)   = 1;
        chrRegionCur1(1,end,end) = 1; chrRegionCur1(end,1,1) = 1; chrRegionCur1(end,1,end) = 1;
        chrRegionCur1(end,end,1) = 1; chrRegionCur1(end,end,end) = 1;
        
        [X,Y,Z]=meshgrid((1:dy)*voxelSizeY,(1:dx)*voxelSizeX,(1:Nz)*voxelSizeZ);
        
        hVol = figure('Name', strcat('Frame: ', num2str(tpoint, '%0.3f')), 'NumberTitle','off', 'Visible', 'off');
        isosurface(X,Y,Z,chrRegionCur1,0.9);
        alpha(0.5)
        isosurface(X,Y,Z,chrRegionCur2,0.7);
        alpha(0.7)
        axis equal
        
        savefile = [dispDir lsmFn(tpoint).name(1:end-4) '_chr.jpg'];
        saveas(hVol, savefile, 'jpg');
        delete(hVol);
    end
    
    %% End of displaying volume and predicting parameters
    tpoint = tpoint + 1;
    clear wsLabel;
    clear distImage;
    clear chrMarker;
    clear X;
    clear Y;
    clear Z;
    clear contourCRegionThreeD;
    close all;
end

%Write the extracte parameters to individual files
paramsFn = fullfile(curOutDir,  exParamsFn);
paramsTable(1,:) = [];
writetable(paramsTable,paramsFn,'Delimiter','\t');
procStat = 1;
end