-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDoTrackSegMStack.m
More file actions
3284 lines (2998 loc) · 138 KB
/
DoTrackSegMStack.m
File metadata and controls
3284 lines (2998 loc) · 138 KB
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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
function [TrackedOut,AllImg,segdataout]=DoTrackSegMStack(directory,channels,crop,timecrop)
%
% [Tracked,AllImg] = DoTrackSeg(dirname,channel, crop, timecrop)
% Track automatically without opening any gui.
% dirname = name of directory containing all movie files. all files
% should be the same stage position.
% e.g.'\Users\ayaron\Movies\2012-01-27\stage1'
% channel = cell array of strings containing the segmentation color
% name. e.g. {'YFP'}
% crop = part of the image to load. [{ystart,yend},{xstart,xend}]
% timecrop = [startframe, endframe]
%
% DoTrackSeg
% DoTrackSeg(Tracked)
% DoTrackSeg(Tracked,AllImg)
% DoTrackSeg(dirname,channel, crop, timecrop)
% Open the GUI to edit the tracking
%definitions for bacterial movies
FileType='';%'','bacteria';
BkgType='';%'','template','bacteria';
BkgPrm=[];%the template if it is a template
SegType='';%'','ear','bacteria','bactear';
global segdata
global gcounter
segdata=[];gcounter=0;
segdataout=segdata;
FromTranalyze=-1;
%global variables
Tracked=[];
AllImg=[];
%
%%%uncomment to make background subtraction occur by including external
%%%files
% SegType='';
% BkgType='template';
% BkgPrm={'C:\Users\zeiss\Documents\MATLAB\bkg\','c1','bkg.tif'};
%determine matfile directory
mdir = mfilename('fullpath');
[~,b ] = regexp(mdir,'/');
if isempty(b)
[~,b] = regexp(mdir,'\');
end
parentdir = mdir(1:b(end)); %folder in which matfile exists
exportdir = strcat(parentdir,'Export/');
[~,b ] = regexp(parentdir,'/');
if isempty(b)
[~,b] = regexp(parentdir,'\');
end
gparentdir = parentdir(1:b(end-1)); %folder in which matfile parentdir exists
%specify important directory names
mstackName = 'flat mstack';
trackName = 'tracking files';
segmentName = 'segment mstack';
%initialize global variables
%set colormap
% user selects experiment directory to be analyzed
%make tracking file folder if it does not exist
%determine date of experiment
%subdirectories should include
%> [ flat mstack ]
%> [ mstack images ]
%> [ segment mstack ]
%> [ tracking files ]
ParseArguments(nargin,nargout)
function ParseArguments(pnumin,pnumout)
if pnumin >4
error('Wrong number of arguments')
end
if pnumout==3
RunManuall;%run a different function that i can change manually
elseif pnumout>0 %automatic Load, Segment, Track, Calculate
if ~exist('directory','var')
%open a directory
directory=uigetdir(pwd,'Select a directory to load files');
elseif ~ischar(directory) || ~isdir(directory)
error('First argument is not a valid directory name')
end
[~,MovieName]=fileparts(directory);
if ~exist('channels','var')
%try to find the possible colors
olddir=pwd;
cd(directory);
f=[dir('*TIF'),dir('*tif')];
[~,~,~,chlist]=regexp([f.name],'c[0-9]*_');
chlist=unique(chlist);
%chlistname=cellfun(@(x) x(3:end), unique(chlist),'unif',0);
chlistname=chlist;
chsel=listdlg('ListString', chlistname, 'SelectionMode','single', 'ListSize',[160,80]);
channels=chlist(chsel);
cd(olddir);
elseif ~iscellstr(channels)
error('Second argument is not a valid cell array of strings')
end
if ~exist('crop','var')
crop=[];
end
if ~exist('timecrop','var')
AutoTrackSeg(directory,channels,crop);
else
AutoTrackSeg(directory,channels,crop,timecrop(1),timecrop(2));
end
TrackedOut=Tracked;
else %Open the GUI
if pnumin==0
%open a directory
directory=uigetdir(pwd,'Select a directory to load files');
end
if ~exist('crop','var')
crop=[];
end
if ishandle(directory) %called by tranalyze
FromTranalyze=directory;
m=guidata(directory);
directory=m.Tracked;
if ~isempty(m.AllImg)
channels=m.AllImg;
pnumin=2;
end
end
if ischar(directory) %should start from files
if ~ischar(directory) || ~isdir(directory)
error('First argument is not a valid directory name or a Tracked structure')
end
if ~exist('channels','var')
%try to find the possible colors
olddir=pwd;
cd(directory);
% load experiment
cd(directory)
experimentdir = directory;
mstackPath = strcat(experimentdir,'/',mstackName);
segmentPath = strcat(experimentdir,'/',segmentName);
trackingPath = strcat(experimentdir,'/',trackName);
%make tracking file folder if it does not exist
cd(experimentdir)
%determine date of experiment
[a,b] = regexp(experimentdir,'201[0-9]');
[~,d] = regexp(experimentdir,'exp[0-9]');
ExpDate = experimentdir(a:b+6);expDateStr = experimentdir(a:d);
[a,~] = regexp(ExpDate,'_');ExpDate(a) = '-';
%%load helpful metadata
cd(exportdir)
FileName = expDateStr;
datequery = strcat(FileName,'*DoseAndScene*');
cd(exportdir)
filelist = dir(datequery);
if isempty(filelist)
error(strcat('need to run ExtractMetadata for-',FileName));
% dosestruct = makeDoseStruct; %run function to make doseStruct
else
dosestructstruct = load(char(filelist.name));
dosestruct = dosestructstruct.dosestruct;
end
segInstruct = dosestructstruct.segInstruct;
nucleus_seg = segInstruct.nucleus;
cell_seg = segInstruct.cell;
background_seg = segInstruct.background;
channelstoinput = dosestructstruct.channelNames;
channelinputs =channelregexpmaker(channelstoinput);
bkg = dosestructstruct.BACKGROUND;
imgsize = dosestructstruct.dimensions;
cd(directory)
% dirname = 'flat mstack';
% dirlog = isdir(dirname);
% if dirlog == false
% error('directory does not contain correct file type')
% end
%
% cd(dirname)
f=[dir('*mat'),dir('*mat')];
[~,~,~,chlist]=regexp([f.name],channelinputs);
%chlist=[chlist{:}];
chlist=unique(chlist);
%chlistname=cellfun(@(x) x(3:end), chlist,'unif',0);
chlistname=chlist;
chsel=listdlg('ListString', chlistname, 'SelectionMode','single', 'ListSize',[160,80]);
channels=chlist(chsel);
cd(olddir);
elseif ~iscellstr(channels)
error('Second argument is not a valid cell array of strings')
end
%do the segmentation
if exist('timecrop','var')
ParSegment(directory,channels,crop,timecrop(1),timecrop(2));
else
ParSegment(directory,channels,crop);
end
elseif iscell(directory) && (pnumin==1 || iscell(channels))%the arguments are the tracked structure and images
Tracked=directory;
if exist('channels','var') && ~isempty(channels)
AllImg=channels;
else %open the images
AllImg=cell(1,length(Tracked));
olddir=pwd;
if ~isdir(Tracked{1}.dirname)
directory=uigetdir(olddir,'Select a new directory with image files');
for i=1:length(Tracked)
Tracked{i}.dirname=[directory filesep];
end
end
cd(Tracked{1}.dirname);
hh=waitbar(0,'Loading Images...');
for cframe=1:length(Tracked)
waitbar(cframe/length(Tracked),hh)
if isfield(Tracked{cframe},'crop')
crop=Tracked{cframe}.crop;
else
Tracked{cframe}.crop=crop;
end
%im_bs=loadImage(Tracked{cframe}.filename,crop,Tracked{cframe}.fit,BkgType);
im_bs=loadImage(Tracked{cframe}.filename,crop,BkgPrm,BkgType);
AllImg{cframe}=im_bs;
end
delete(hh)
end
else
error('Wrong arguments')
end
if ishandle(FromTranalyze)
DisplayTrack(m.cframe,m.ccell);
uiwait
m=[];
m.Tracked=Tracked;
m.AllImg=AllImg;
guidata(FromTranalyze,m)
else
DisplayTrack;
end
end
end
function AutoTrackSeg(directory,channels,crop,framestart,framestop)
olddir=pwd;
cd(directory);
directory=[pwd filesep];
imagefiles={};
for cchannel=channels
filelist=dir(['*' char(cchannel) '*']);
switch FileType
case 'bacteria'
fieldpos=strfind(filelist(1).name,'-')+1;
fieldpos=fieldpos(end);
[~,I]=sort(arrayfun(@(x) str2num(x.name(fieldpos:end-4)), filelist));
otherwise
%directly from metamorph
%used to sort by name, now try to sort by date. this
%allows for movies that were interupted and then
%continued
%%[~,~,~,~,fieldpos]=regexp({filelist.name},'_t([^_]+)[\._]');
%%fieldpos=[fieldpos{:}];fieldpos=[fieldpos{:}];
%%[~,I]=sort(cellfun(@(x) str2num(x),fieldpos));
[~,I]=sort(arrayfun(@(x) datenum(x.date), filelist));
end
imagefiles(end+1,:)={filelist(I).name};
end
if ~exist('framestart') || ~exist('framestop') || framestop>length(imagefiles)
framestart=1;
framestop=length(imagefiles);
end
isWorker=~isempty(getCurrentWorker);
if ~isWorker
h=waitbar(0,'Starting AutoTrackSeg...');
else
disp(sprintf('%s: Starting AutoTrackSeg...',directory))
end
Tracked=cell(1,framestop-framestart+1);
AllImg=cell(1,framestop-framestart+1);
for imagenb=framestart:framestop
Tracked{imagenb}.filename=imagefiles(:,imagenb);
Tracked{imagenb}.crop=crop;
Tracked{imagenb}.timecrop=[framestart,framestop];
%Load and Segment the image
if ~isWorker
waitbar((imagenb-1)/length(imagefiles),h,sprintf('Segmenting Image %d',imagenb));
else
disp(sprintf('%s: Segmenting Image %d',directory,imagenb))
end
[ccell,cimg,cfit]=SegmentFile(imagefiles(:,imagenb),crop,BkgPrm,BkgType,SegType);
AllImg{imagenb}=cimg;
Tracked{imagenb}.cells=num2cell(ccell);
Tracked{imagenb}.filename=imagefiles(:,imagenb);
Tracked{imagenb}.dirname=directory;
Tracked{imagenb}.Locked=0;
Tracked{imagenb}.predictMito=0;
Tracked{imagenb}.fit=cfit;
%Track the image
if ~isWorker
waitbar((imagenb-2/3)/length(imagefiles),h,sprintf('Tracking Image %d',imagenb));
else
disp(sprintf('%s: Tracking Image %d',directory,imagenb))
end
if imagenb==framestart
cells1=[Tracked{framestart}.cells{:}];
cells1=CalcCellProperties(cells1,AllImg{imagenb});
Tracked{imagenb}.Locked=0;
Tracked{imagenb}.cells=num2cell(cells1);
else
cells0=[Tracked{imagenb-1}.cells{:}];
cells1=[Tracked{imagenb}.cells{:}];
imn0=AllImg{imagenb-1};
imn1=AllImg{imagenb};
predictMito=Tracked{imagenb}.predictMito;
[cells0,cells1,predictMito]=TrackFrame(imn0,cells0,imn1,cells1,predictMito);
Tracked{imagenb-1}.cells=num2cell(cells0);
Tracked{imagenb-1}.Locked=1;
Tracked{imagenb}.Locked=0;
Tracked{imagenb}.predictMito=predictMito;
Tracked{imagenb}.cells=num2cell(cells1);
end
%calulate extra fluorescence channels
if ~isWorker
waitbar((imagenb-1/3)/length(imagefiles),h,sprintf('Calculate Fluorescence for Image %d',imagenb));
else
disp(sprintf('%s: Calculate Fluorescence for Image %d',directory,imagenb))
end
CalcFluorescence(imagenb,imagenb,1)
end
if ~isWorker
delete(h)
else
disp(sprintf('%s: Finished Tracking',directory))
end
cd(olddir)
end
function RunManuall
end
function ParSegment(directory,channels,crop,framestart,framestop)
olddir=pwd;
cd(directory);
directory=[pwd filesep];
imagefiles={};
for cchannel=channels
filelist=[dir(['*' char(cchannel) '*.mat']) dir(['*' char(cchannel) '*.MAT'])];
% filelist=filelist(:);
filelist=filelist(1);
[~,ia]=unique({filelist.name});
filelist=filelist(ia);
switch FileType
case 'bacteria'
fieldpos=strfind(filelist(1).name,'-')+1;
fieldpos=fieldpos(end);
[~,I]=sort(arrayfun(@(x) str2num(x.name(fieldpos:end-4)), filelist));
otherwise %directly from metamorph
%used to sort by name, now try to sort by date. this
%allows for movies that were interupted and then
%continued
%%[~,~,~,~,fieldpos]=regexp({filelist.name},'_t([^_]+)[\._]');
%%fieldpos=[fieldpos{:}];fieldpos=[fieldpos{:}];
%%[~,I]=sort(cellfun(@(x) str2num(x),fieldpos));
[~,I]=sort(arrayfun(@(x) datenum(x.date), filelist));
end
imagefiles(end+1,:)={filelist(I).name};
end
cfilename = imagefiles{1};
mfile = matfile(char(cfilename));
imstack = mfile.flatstack;
Tracked=cell(1,length(imagefiles));
for imagenb=1:size(imstack,3)
Tracked{imagenb}.filename=imagefiles(:,1);
end
if ~exist('framestart') || ~exist('framestop') || framestop>size(imstack,3)
framestart=1;
framestop=size(imstack,3);
end
ppool = gcp;
parallel=ppool.NumWorkers;
AllImg=cell(1,length(Tracked));
if parallel==0
h=waitbar(0,'Segmenting Images...');
else
h=[];
disp('Segmenting Images...')
end
parfor imagenb=framestart:framestop
% for imagenb=framestart:framestop
if parallel==0
waitbar((imagenb-framestart)/(framestop-framestart),h,sprintf('Segmenting Image %d',imagenb));
else
disp(sprintf('Segmenting Image %d',imagenb));
end
Tracked{imagenb}.crop=crop;
Tracked{imagenb}.timecrop=[framestart,framestop];
[ccell,cimg,cfit]=SegmentFile(imstack(:,:,imagenb),crop,BkgPrm,BkgType,SegType);
AllImg{imagenb}=cimg;
Tracked{imagenb}.cells=num2cell(ccell);
Tracked{imagenb}.filename=cfilename;
Tracked{imagenb}.dirname=directory;
Tracked{imagenb}.Locked=0;
Tracked{imagenb}.predictMito=0;
Tracked{imagenb}.fit=cfit;
%display(['Image ' imagefiles{imagenb} ', ' num2str(length(Tracked{imagenb}.cells)) ' cells.']);
end
if parallel==0
delete(h)
end
cd(olddir)
end
function TrackAll(framestart,framestop)
cells1=[Tracked{framestart}.cells{:}];
predictMito=Tracked{framestart}.predictMito;
%tic
h=waitbar(0,'Tracking...');
for cframe=framestart:framestop
waitbar((cframe-framestart)/(framestop-framestart),h,['frame ' num2str(cframe) ', cells: ' num2str(length(Tracked{cframe}.cells))]);
%display(['frame ' num2str(cframe) ', cells: ' num2str(length(Tracked{cframe}.cells))])
cells0=cells1;
cells1=[Tracked{cframe+1}.cells{:}];
if ~(Tracked{cframe}.Locked && Tracked{cframe+1}.Locked)
imn0=AllImg{cframe};
imn1=AllImg{cframe+1};
predictMito=Tracked{cframe}.predictMito;
[cells0,cells1,predictMito]=TrackFrame(imn0,cells0,imn1,cells1,predictMito);
Tracked{cframe}.cells=num2cell(cells0);
Tracked{cframe}.Locked=1;
Tracked{cframe+1}.Locked=0;
Tracked{cframe+1}.predictMito=predictMito;
end
Tracked{cframe+1}.cells=num2cell(cells1);
if ~ishandle(h)
return
end
end
delete(h);
%display(sprintf('finished %.3f', toc))
end
function [cells0,cells1,predictMito]=TrackFrame(imn0,cells0,imn1,cells1,predictMito)
recalculate=0;
[imy,imx]=size(imn1);
% find registration shift on the mask image
%pixel [1,1] of the second image is pixel [1,1]+regshift of the
%first. generally move the first image coords to the second image
%frame by subtracting regshift
xcorrim0=min(1,SegRenderNum(cells0,imy,imx));
xcorrim1=min(1,SegRenderNum(cells1,imy,imx));
nres=5;
if max(max(xcorrim0))==0 || max(max(xcorrim1))==0
%no cells were segmented
regshift=[0,0];
else
xc=xcorr2(xcorrim0(1:nres:end,1:nres:end),xcorrim1(1:nres:end,1:nres:end)); %compute low resolution cross correlation
[I,J]=find(xc==max(xc(:)),1);
regshift=nres*[I,J]-[imy,imx]; %determine how far the maxima in the image moves, i think by computing cross correlation
end
% if regshift is small just ignore it
if max(abs(regshift))<10
regshift=[0,0];
end
% Calculate cell properties
% assume existing: pos, size, mask
% calculate additional: area, Acom (area-center-of-mass), Ftotal, Fmean, Fmax, Fpixels, slice
nbcell0=length(cells0); %number of cells in cells0
nbcell1=length(cells1);
cells0=CalcCellProperties(cells0,imn0);
cells1=CalcCellProperties(cells1,imn1);
% First step: match cells in frame 0 to segments in frame 1.
% do it by 1. split mitoting cells
% 2. map cells into segments according to distance.
% allow multiple cells to be merged if there is enough energy.
% 3. check the asignment
%0. if no cells try to look for them
if nbcell1==0
for dcell=1:nbcell0 %iterate through the number of cells in image0
position=min(max(cells0(dcell).pos+cells0(dcell).Acom-[51,51]-regshift,1),[imy,imx]);
eposition=min(position+100,[imy,imx]);
imreg=imn1(position(1):eposition(1)-1,position(2):eposition(2)-1);
if isempty(imreg)
continue
end
ll=localsegment(medfilt2(imreg,[5,5],'symmetric'),SegType);
[ll2,nn]=bwlabel(ll,8);
stats = regionprops(ll2, imreg, 'meanIntensity','area','BoundingBox');
%check that it is similar size and level
similaritydist=([stats.MeanIntensity]/cells0(dcell).Fmean-1).^2/0.04+([stats.Area]/cells0(dcell).area-1).^2/0.04;
overlapdist=zeros(size(similaritydist));
origcellreg=SegRenderNum(cells0(dcell),imy,imx);
origcellreg=origcellreg(position(1):eposition(1)-1,position(2):eposition(2)-1);
overlapIdx=unique(origcellreg.*ll2);
overlapdist(overlapIdx(2:end))=1;
candict=struct('mask',{},'pos',{},'size',{},'progenitor',{},'descendants',{});
%for cand=find(similaritydist<4/pi | overlapdist)
for cand=find(similaritydist<3*4/pi)
cellslice=[ceil(stats(cand).BoundingBox(2:-1:1)) ceil(stats(cand).BoundingBox(2:-1:1))+stats(cand).BoundingBox(4:-1:3)-1];
cellmask=ll2(cellslice(1):cellslice(3),cellslice(2):cellslice(4))==cand;
cellpos=position+cellslice(1:2);
candict(end+1)=struct('mask',cellmask,'pos',cellpos,'size',size(cellmask),'progenitor',[],'descendants',[]);
end
if size(candict)==0
continue
end
candict=CalcCellProperties(candict,imn1);
%should also check that it is not an existing segment (does not overlap with anything)
overlapcand = any(CalcCellPairProperties(candict,cells1,length(candict),nbcell1)>0,2);
candict=candict(~overlapcand);
%imshow(SegRender(candict,imx,imx)+2*SegRender(cells1,imx,imx));show()
if isempty(candict)
continue
end
% and if more than one candidate, take the closest one
% maybe later just recompute from scratch
[~,canddist]=CalcCellPairProperties(candict,cells0(dcell),length(candict),1);
[~,candselect]=min(canddist);
if isempty(cells1)
cells1=candict(candselect);
else
cells1(end+1)=candict(candselect);
end
nbcell1=nbcell1+1;
end
end
if nbcell1==0
predictMito=[];
return
end
if nbcell0==0
predictMito=zeros(1,nbcell1);
return
end
%1. split mitoting cells. used to predict mitosis. not done
%anymore.
% keep original cell for mitoting cells
OrigCell=[];
predictMito=[];
%if any(predictMito)
% for j=find(predictMito)
% cells0(end+1)=cells0(j); %LB: this is failing sometimes (j>length(cells0))
% cells0(end).Fmask=0.5*cells0(end).Fmask;
% cells0(j).Fmask=0.5*cells0(j).Fmask;
% OrigCell(end+1)=j;
% end
% nbcell0=length(cells0);
% cells0=CalcCellProperties(cells0,imn0);
%end
%2. map cells
%Calculate properties of cell pairs: overlap, and distance
[overlap,celldistance]=CalcCellPairProperties(cells0,cells1,nbcell0,nbcell1,regshift);
%Calculate the cost functions
overlapnorm0=bsxfun(@rdivide,overlap,[cells0.area]');
fmapping=bsxfun(@ldivide,[cells0.Ftotal]',0.9*[cells1.Ftotal]);
cost=overlapnorm0+1./sqrt(512/imx*celldistance+1);
fused=zeros(nbcell0,nbcell1);
%cost=bsxfun(@rdivide,overlapnorm0,sum(overlapnorm0))+1./sqrt(512/imx*celldistance+1);
%find the mapping
cellmapping=zeros(nbcell0,nbcell1);
cellscore=zeros(nbcell0,nbcell1);
mappedcells=zeros(1,nbcell0);
NNmapping=1;
HAmapping=1;
%if have some links use them
for ccell=1:nbcell0
if isempty(cells0(ccell).descendants)
elseif isscalar(cells0(ccell).descendants)
cellmapping(ccell,cells0(ccell).descendants)=1;
else %assume 2 descendants
cellmapping(ccell,cells0(ccell).descendants(1))=1;
cellmapping(end+1,:)=0;
cellmapping(end,cells0(ccell).descendants(2))=1;
cells0(end+1)=cells0(ccell);
usedpercent=[cells1(cells0(ccell).descendants).Ftotal]./cells0(ccell).Ftotal;
cells0(ccell).Fmask=usedpercent(1)*cells0(ccell).Fmask;
cells0(end).Fmask=usedpercent(2)*cells0(end).Fmask;
cellscore(end+1,:)=0;
mappedcells(end+1)=0;
fmapping(end+1,:)=fmapping(ccell,:)/usedpercent(2);
fmapping(ccell,:)=fmapping(ccell,:)/usedpercent(1);
cost(end+1,:)=cost(ccell,:);
OrigCell(end+1)=ccell;
recalculate=1;
end
end
nbcell0=length(cells0);
fused=cellmapping.*fmapping;
cellscore=cellmapping.*cost.*fmapping;
mappedcells=sum(cellmapping,2);
%complete the mapping
while sum(NNmapping(:).*HAmapping(:))>0
fresidue=bsxfun(@times,fmapping,(1-sum(cellmapping./fmapping)));
fresidue=min(max(fresidue,0.001),1);%cut it at 1 and 0.001
fcost=cost.*fresidue.*fresidue;
%prefer orphan segments
%fcost=bsxfun(@plus,fcost,0.1*(1-sum(cellmapping)));
fcost=fcost+bsxfun(@times,fcost,0.1*(1-sum(cellmapping)));
%maybe square it maybe not. for cells that have divided once definitly should be hard to divide again.
% fcost=cost*((fmapping*(1-sum(cellmapping/fmapping,axis=0)))**2).clip(max=1,min=0.001)
fcost(mappedcells==1,:)=0.0001;
NNmapping=zeros(nbcell0,nbcell1);
[~,tmp]=max(fcost,[],2);
NNmapping(sub2ind(size(fcost),1:nbcell0,tmp'))=1;
%HAmapping=CalcHungarian(1./fcost);
HAmapping=CalcHungarian(1./max(fcost,0.0001),1/0.01);
cellmapping=cellmapping+NNmapping.*HAmapping;
cellscore=cellscore+NNmapping.*HAmapping.*fcost;
mappedcells=sum(cellmapping,2);
%how much of the energy of the original cell is mapped to the
%new cell
fused=fused+NNmapping.*HAmapping.*fresidue;
%if a cell mapped to a low energy segment it probably mitosed so remove .5 of the energy and keep it unmapped
%TBD: maybe it was mapped to an undersegmented cell. check segmentation.
for mitcell=find(sum((fused<0.66).*cellmapping,2))'
% display('here, please check this code again')
% continue
usedpercent=fused(mitcell,cellmapping(mitcell,:)==1);
cells0(end+1)=cells0(mitcell);
%maybe 0.9-used and 0.1+used
cells0(end).Fmask=(1-usedpercent)*cells0(end).Fmask;
cells0(mitcell).Fmask=(usedpercent)*cells0(mitcell).Fmask;
nbcell0=nbcell0+1;
cellmapping(end+1,:)=0;
cellscore(end+1,:)=0;
mappedcells(end+1)=0;
fmapping(end+1,:)=fmapping(mitcell,:)/(1-usedpercent);
fmapping(mitcell,:)=fmapping(mitcell,:)/usedpercent;
fused(end+1,:)=0;
fused(mitcell,:)=fused(mitcell,:)/usedpercent;
cost(end+1,:)=cost(mitcell,:);
OrigCell(end+1)=mitcell;
recalculate=1;
end
end
% check if i mapped something into the noise. that is, if a dim object mapped into a bright one.
% check both Ftotal ratio <5 and Fmean ratio <3
FtotalR=cellmapping*[cells1.Ftotal]'./[cells0.Ftotal]';
FmeanR=cellmapping*[cells1.Fmean]'./[cells0.Fmean]';
tmpcellmapping=cellmapping;
tmpcellmapping((FtotalR>5) & (FmeanR>3),:)=0;
areaR=cellmapping*([cells0.area]*tmpcellmapping./[cells1.area])';
% TBD: it is really a noise if its level is only a fraction of the pixels it cover
cellmapping((FtotalR>5) & (FmeanR>3) & (areaR>0.85),:)=0;
% if it disappears try to look for it
for dcell=find(sum(cellmapping,2)==0)'
position=min(max(cells0(dcell).pos+cells0(dcell).Acom-[51,51]-regshift,1),[imy,imx]);
eposition=min(position+100,[imy,imx]);
imreg=imn1(position(1):eposition(1)-1,position(2):eposition(2)-1);
if isempty(imreg)
continue
end
ll=localsegment(medfilt2(imreg,[5,5],'symmetric'),SegType);
[ll2,nn]=bwlabel(ll,8);
stats = regionprops(ll2, imreg, 'meanIntensity','area','BoundingBox');
%check that it is similar size and level
similaritydist=([stats.MeanIntensity]/cells0(dcell).Fmean-1).^2/0.04+([stats.Area]/cells0(dcell).area-1).^2/0.04;
overlapdist=zeros(size(similaritydist));
origcellreg=SegRenderNum(cells0(dcell),imy,imx);
origcellreg=origcellreg(position(1):eposition(1)-1,position(2):eposition(2)-1);
overlapIdx=unique(origcellreg.*ll2);
overlapdist(overlapIdx(2:end))=1;
if ~isempty(cells1)
emptycell=struct(cells1(end));
for cfield=fieldnames(emptycell)'
emptycell.(cfield{1})=[];
end
else
emptycell=struct('mask',[],'pos',[],'size',[],'progenitor',[],'descendants',[]);
end
candict=emptycell;
%for cand=find(similaritydist<4/pi | overlapdist)
for cand=find(similaritydist<3*4/pi)
cellslice=[ceil(stats(cand).BoundingBox(2:-1:1)) ceil(stats(cand).BoundingBox(2:-1:1))+stats(cand).BoundingBox(4:-1:3)-1];
cellmask=ll2(cellslice(1):cellslice(3),cellslice(2):cellslice(4))==cand;
cellpos=position+cellslice(1:2);
candict(end+1)=emptycell;
candict(end).mask=cellmask;
candict(end).pos=cellpos;
candict(end).size=size(cellmask);
end
candict(1)=[];
if isempty(candict)
continue
end
candict=CalcCellProperties(candict,imn1);
%should also check that it is not an existing segment (does not overlap with anything)
overlapcand = any(CalcCellPairProperties(candict,cells1,length(candict),nbcell1)>0,2);
candict=candict(~overlapcand);
%imshow(SegRender(candict,imx,imx)+2*SegRender(cells1,imx,imx));show()
if isempty(candict)
continue
end
% and if more than one candidate, take the closest one
% maybe later just recompute from scratch
[~,canddist]=CalcCellPairProperties(candict,cells0(dcell),length(candict),1);
[~,candselect]=min(canddist);
cells1(end+1)=candict(candselect);
nbcell1=nbcell1+1;
cellmapping(:,end+1)=0;
cellmapping(dcell,end)=1;
recalculate=1;
end
% if two predicted mitotic cells are mapped to the same segment, don't mitose
addedCells=length(OrigCell);
for mitocellnum=1:addedCells
mitocell=OrigCell(addedCells+1-mitocellnum);
mitocellsister=nbcell0-mitocellnum+1;
if all(cellmapping(mitocell,:)==cellmapping(mitocellsister,:))
OrigCell(addedCells+1-mitocellnum)=[];
cells0(mitocell).Fmask=cells0(mitocell).Fmask+cells0(mitocellsister).Fmask;
cells0(mitocellsister)=[];
%renumber the OrigCell numbers since we removed a cell
OrigCell(OrigCell==mitocellsister)=mitocell;
OrigCell(OrigCell>mitocellsister)=OrigCell(OrigCell>mitocellsister)-1;
cellmapping(mitocellsister,:)=[];
recalculate=1;
end
end
if recalculate==1
nbcell0=length(cells0);
cells0=CalcCellProperties(cells0,imn0);
[overlap,celldistance]=CalcCellPairProperties(cells0,cells1,nbcell0,nbcell1,regshift);
overlapnorm0=bsxfun(@rdivide,overlap,[cells0.area]');
recalculate=0;
end
% 3. split cells
% if two cells map to the same segment, split it
% three options. touching, partiall overlapp or one withing the other.
SplitOrigCell=1:nbcell1;
AllOrigSeed=[];
for j=find(sum(cellmapping)>1)
seeds={};
abscell=find(cellmapping(:,j));
shifts=bsxfun(@plus,cell2mat({cells0(abscell).pos}'),-cells1(j).pos+[50,50]-regshift);
change=[0,0;0,-1;1,0;-1,0;0,1];
Target=zeros([100,100]+size(cells1(j).Fpixels));
Target=AddCell(Target,[0,0],cells1(j).Fpixels,[50,50]);
OMtmp=zeros(size(Target));
OM=zeros(size(Target));
%start with overlapping cells. maybe take only >0.2 overlapnorm0
for cell=find(overlap(abscell,j))'
OM=AddCell(OM,[0,0],cells0(abscell(cell)).Fpixels,shifts(cell,:));
end
%move them around until they fit best
origshifts=zeros(size(shifts));
while any(any(origshifts~=shifts))
origshifts=shifts;
for cell=find(overlap(abscell,j))'
score=[];
OM=AddCell(OM,[0,0],-cells0(abscell(cell)).Fpixels,shifts(cell,:));
for shft=change'
OM=AddCell(OM,[0,0],cells0(abscell(cell)).Fpixels,shifts(cell,:)+shft');
score(end+1)=sum(sum(abs((OM-Target)./(OM+Target+1))));
OM=AddCell(OM,[0,0],-cells0(abscell(cell)).Fpixels,shifts(cell,:)+shft');
end
shifts(cell,:)=shifts(cell,:)+change(find(score==min(score),1),:);
OM=AddCell(OM,[0,0],cells0(abscell(cell)).Fpixels,shifts(cell,:));
end
end
%add them to a seed list
OrigSeed=[];
for cell=find(overlap(abscell,j))'
seeds{end+1}=AddCell(zeros(cells1(j).size),[0,0],cells0(abscell(cell)).mask,shifts(cell,:)-[50,50]);
seeds{end}=seeds{end}.*cells1(j).mask;
OrigSeed(end+1)=abscell(cell);
end
% now add the non overlapping cells
for cell=find(overlap(abscell,j)==0)'
% find the minima of missing energy
[I,J]=find((imerode(OM-Target,cells0(abscell(cell)).mask)==OM-Target).*(Target>0));
candidatePos=[I,J];
%if it is empty take the minimal one.
if isempty(candidatePos)
[~,tmp]=min(OM(:)-Target(:));
[I,J]=ind2sub(size(Target),tmp);
candidatePos=[I,J];
end
%find the closest one
[~,candidate]=min(sum(bsxfun(@minus,candidatePos,shifts(cell,:)+cells0(abscell(cell)).Acom).^2,2));
OMtmp(candidatePos(candidate,1),candidatePos(candidate,2))=1;
OMtmp=bwlabel((OM-Target)<min(min(OM-Target))/2);
blobn=OMtmp(candidatePos(candidate,1),candidatePos(candidate,2));
OMtmp=(OMtmp==blobn);
while sum(sum(OMtmp.*Target)) < cells0(abscell(cell)).Ftotal
prevsize=sum(sum(OMtmp));
OMtmp=imdilate(OMtmp,strel('diamond',1)).*(Target>0);
if prevsize==sum(sum(OMtmp))
break
end
end
OM=AddCell(OM,[0,0],OMtmp.*Target,[0,0]);
seeds{end+1}=AddCell(zeros(cells1(j).size),[0,0],OMtmp(51:end,51:end),[0,0]).*cells1(j).mask;
OrigSeed(end+1)=abscell(cell);
end
% take the cells and expand, adding unasociated pixels
targetarea=cells1(j).area;
allseeds=sum(cat(3, seeds{:}),3)>0;
seedsarea=sum(sum( allseeds>0 ));
while seedsarea<targetarea
for n=1:length(seeds)
seeds{n}=imdilate(seeds{n},ones(3,3)).*cells1(j).mask.*(1-allseeds)+seeds{n};
end
allseeds=sum(cat(3, seeds{:}),3)>0;
if seedsarea==sum(sum(allseeds));
disp('may have some broken cell. check err20120604.')
break;%no area change, infinite loop;
end
seedsarea=sum(sum( allseeds ));
end
% add the new cells to the dictionary
% if n cells are overlapping, split the F between all
fmeanseeds=[];
fmeanseeds(1,1,:)=[cells0(OrigSeed).Fmean];
fmeanseeds=sum(bsxfun(@times,cat(3, seeds{:}),fmeanseeds),3);
numseeds=sum(cat(3, seeds{:}),3);
for seednum=1:length(seeds)
cell=seeds(seednum);
if ~any(any(cell{1}))
continue
end
tmp=zeros(size(cell{1})+2);
tmp(2:end-1,2:end-1)=cell{1};
tmp=imopen(tmp,strel('diamond', 4));
if any(any(tmp(2:end-1,2:end-1)))
cellOpen=tmp(2:end-1,2:end-1);
else
cellOpen=cell{1};
end
bbox=regionprops(cellOpen,'BoundingBox');
cellslice={floor(bbox.BoundingBox(2))+1:floor(bbox.BoundingBox(2)+bbox.BoundingBox(4)),...
floor(bbox.BoundingBox(1))+1:floor(bbox.BoundingBox(1)+bbox.BoundingBox(3))};
cells1(end+1).mask=cellOpen(cellslice{1},cellslice{2});
cells1(end).pos=cells1(j).pos+floor(bbox.BoundingBox(2:-1:1));
cells1(end).Fmask=cells1(end).mask.*cells0(OrigSeed(seednum)).Fmean./fmeanseeds(cellslice{1},cellslice{2});
%NaN could appear where numseeds is zero. also cell mask is
%zero there and it should just be zero
cells1(end).Fmask(isnan(cells1(end).Fmask))=0;
cells1(end).size=size(cells1(end).mask);
SplitOrigCell(end+1)=j;
AllOrigSeed(end+1)=OrigSeed(seednum);
end
end
% remove the old ones, and recalculate everthing
if any(sum(cellmapping)>1)
todelete=sum(cellmapping)>1;
cells1(todelete)=[];
for i=1:length(AllOrigSeed)
cellmapping(:,end+1)=0;
cellmapping(AllOrigSeed(i),end)=1;
end
SplitOrigCell(todelete)=[];
cellmapping(:,todelete)=[];
nbcell1=length(cells1);
cells1=CalcCellProperties(cells1,imn1);
[overlap,celldistance]=CalcCellPairProperties(cells0,cells1,nbcell0,nbcell1,regshift);
overlapnorm0=bsxfun(@rdivide,overlap,[cells0.area]');
recalculate=0;
end
% Build the mapping:
% now we should have nbcell0=nbcell1
% we might want to allow cells to apear or disappear but we'll see
% if i have a ghost from the previous frame i would try to map all the others and then use it. so give it a cost of 0
% if nbcell1 is bigger, there are new cells. i will pad with zero rows. these assignments won't give me any gain so i will try to maximize assigmnment to 'real' cells and only the others will be assigned here.
% if nbcell0 is bigger, cells turns into ghosts. again, i will pad with 0.
cost=(overlapnorm0+1./sqrt(512/imx*celldistance+1));
fmapping=bsxfun(@ldivide,[cells0.Ftotal]',0.9*[cells1.Ftotal]);
newcellmapping=CalcHungarian(-cost./exp(abs(log(fmapping))),-0.02);
%%try to rebuild the matrix for the original unsplitted cells and
%%see it it is the same as before
%unsplitcellmapping=zeros(nbcell0,max(SplitOrigCell));
%for j=1:nbcell1
% unsplitcellmapping(:,SplitOrigCell(j))=unsplitcellmapping(:,SplitOrigCell(j))+newcellmapping(:,j);
%end
%if ~all(all(newcellmapping==cellmapping))
% disp('There might be a problem in the tracking')
%end
%cellmapping=newcellmapping;
%cellmapping=CalcHungarian(1./(cost.*fmapping.*fmapping));
% Predict Mito in the next frame add 0.01 so as not to divide by zero
FmeanRatio=[cells0.Fmean]*cellmapping./[cells1.Fmean];
FtRatio=[cells0.Ftotal]*cellmapping./[cells1.Ftotal];
areaRatio=[cells0.area]*cellmapping./[cells1.area];
% fix cell mapping for the mitotic cells
% merge back into the original cell
for mitocell=OrigCell(end:-1:1)
cellmapping(mitocell,:)=0.5*(cellmapping(mitocell,:)+cellmapping(end,:));
cellmapping=cellmapping(1:end-1,:);
cells0(mitocell).Fmask=cells0(mitocell).Fmask+cells0(end).Fmask;
cells0(end)=[];
nbcell0=nbcell0-1;
recalculate=1;
end
if recalculate==1
nbcell0=length(cells0);
cells0=CalcCellProperties(cells0,imn0);
recalculate=0;
end
predictMito=areaRatio>1.43;
% if a mito wasn't predicted but a cell have much less size and F, plus there was an appearing cell, there was a mito
% # for cell in predictMito.nonzero()[0]:
for cell=find(FtRatio>1.43)
origcell= find(cellmapping(:,cell));
%is there a relatively close appearing cell
for newcell=find((cost(origcell,:)>0.2) & (sum(cellmapping)==0))
%associate it as a descendant
cellmapping(origcell,newcell)=0.5;
cellmapping(origcell,cell)=0.5;
end
end
predictMito = predictMito & (sum(cellmapping)==1);
% if a cell mitosed into two daughters that touch
% remerge the daughters
%if mitosed into three, unlink random daugter
cellstoremove=[];
for cell=1:nbcell0
descend=find(cellmapping(cell,:));
if length(descend)>1
if length(descend)>2
cellmapping(cell,descend)=0.5;
for cdes=3:length(descend)
cellmapping(cell,descend(cdes))=0;
end
descend=find(cellmapping(cell,:));
end
descend_overlap=sum(sum(SegRenderCnt(cells1(descend))==2));
if descend_overlap>0 && 1<0 %never do that