-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuiSegmentTimeLapseImages.m
More file actions
1386 lines (1110 loc) · 39.3 KB
/
uiSegmentTimeLapseImages.m
File metadata and controls
1386 lines (1110 loc) · 39.3 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 uiSegmentTimeLapseImages
global mstackPath subaxestwo channelList segInstructList segmentList pStruct subaxes exportdir seginputs channelinputs adjuster cmapper tcontrast lcontrast OGExpDate cmap A AA timeFrames ImageDetails SceneList imgsize ExpDate
adjuster=0;
tcontrast = 99;
lcontrast = 1;
clearvars -global SceneDirectoryPath
ImageDetails = InitializeImageDetails;
%%% set colormap for the images %%%
cmap = colormap(gray(255));
% cmap = colormap(magma(255));
% cmap = colormap(inferno(255));
% cmap = colormap(plasma(255));
cmap(255,:)=[1 0 0];
cmapper = cmap;
close all
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%choose directory of experiment to track
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%set directory to location of code being used (generally external harddrive
%%%%
%determine path to .m file being executed
mdir = mfilename('fullpath');
[~,b] = regexp(mdir,'Tracking\w*/');
if isempty(b)
[~,b] = regexp(mdir,'Tracking\w*\');
end
parentdir = mdir(1:b);
exportdir = strcat(parentdir,'Export/');
%determine path to gparent folder
[~,b ] = regexp(parentdir,'/');
if isempty(b)
[~,b] = regexp(parentdir,'\');
end
gparentdir = parentdir(1:b(end-1));
cd(parentdir)
cd ..
%set parent directory from user input
A = uigetdir;
AA = 'D:\Users\zeiss\Documents\MATLAB';
cd(A)
mstackName = 'flat mstack';
experimentdir = A;
mstackPath = strcat(experimentdir,'/',mstackName);
%subdirectories should include
%> [ flatfield_corrected ]
%> [ ####date## smad3g smFISH_scene_s## ]
%> [ c#_flat ] [ tiffs ]
%need to load up the NucleusBinary_flat images
%determine date of experiment
cd (mstackPath)
[a,b] = regexp(A,'201[0-9]');
[c,d] = regexp(A,'exp[0-9]+');
ExpDate = A(a:b+6);OGExpDate = A(a:d); [a,~] = regexp(ExpDate,'_');ExpDate(a) = '-';
disp(A)
%load associated metadata
FileName = OGExpDate;
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
channelstoinput = dosestructstruct.channelNameSwapArray;
channelinputs =channelregexpmaker(channelstoinput);
bkg = dosestructstruct.BACKGROUND;
imgsize = dosestructstruct.dimensions;
segInstruct = dosestructstruct.segInstruct;
fnames = fieldnames(segInstruct);
segmentList = cell(1,length(fnames));
segmentListDisp = cell(1,length(fnames));
segInstructList = cell(1,length(fnames));
for i = 1:length(segmentList)
str = fnames{i};
segmentListDisp{i} = [str '-' segInstruct.(str)];
segmentList{i} = segInstruct.(str);
segInstructList{i} = str;
end
seginputs = channelregexpmaker(fnames);
%set up regexp parameters
BACKGROUND = bkg{1};
bkarray = bkarraymaker(BACKGROUND); %'(s01|s02|s03)'
bkinputs =channelregexpmaker(bkarray); %'(chanstrA|chanstrB|chanstrC)'
%determine how many scenes are present
dirlist = dir(mstackPath);
[~,~,~,d] = regexp({dirlist.name},'s[0-9]++');
dlog = ~cellfun(@isempty,d,'UniformOutput',1);
dcell = d(dlog);
SceneList = unique(cellfun(@(x) x{1},dcell,'UniformOutput',0));
%remove background scenes from list
[~,~,~,d] = regexp(SceneList,bkinputs);
bkgscenelog = cellfun(@isempty,d,'UniformOutput',1);
SceneList = SceneList(bkgscenelog);
%determine the number of time frames per scene
cd(A)
cd(mstackPath)
filelist = dir('*.mat');
fnames = {filelist.name};
fileName = fnames{1};
fileObject = matfile(fileName);
dim = size(fileObject,'flatstack');
if max(size(dim))>2
timeFrames = dim(3);
else
timeFrames = 1;
end
%determine the number of channels
folderlist = dir(strcat('*','*'));
channelinputs =channelregexpmaker(channelstoinput);
[~,~,~,channelsListed] = regexp([folderlist.name],channelinputs);
channelList = unique(channelsListed);
for i=1:length(channelList)
chan = channelsListed{i};
[a,~] = regexp(chan,'_');
chan(a) = [];
channelList{i} = chan;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%Set up user interface
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
f = figure;
% f.Visible ='off';
f.Units = 'pixels';
f.Position =[70 90 1800 900];
bW = 80; %buttonWidth
sW = 10; %spacerWidth
bH = 50; %buttonHeigth
%row1
% hNextFrame
xPi = 1500;
yPi = 850;
xP = xPi;
yP = yPi;
uicontrol('Style','pushbutton','String','NextFrame [f]',...
'Position',[xP,yP,bW,bH],...
'Callback',@nextbutton_callback);
% hPreviousFrame
xP = xP+sW+bW;
uicontrol('Style','pushbutton','String','Previous frame [a]',...
'Position',[xP,yP,bW,bH],...
'Callback',@prevbutton_callback);
% hGoToFrame
xP = xP+sW+bW;
uicontrol('Style','pushbutton','String','Go to Frame',...
'Position',[xP,yP,bW,bH],...
'Callback',@gotobutton_callback);
%row2
% hFirstFrame
xP = xPi;
yP = yP-bH-sW;
uicontrol('Style','pushbutton','String','First frame [z]',...
'Position',[xP,yP,bW,bH],...
'Callback',@firstbutton_callback);
% hFinalFrame
xP = xP+sW+bW;
uicontrol('Style','pushbutton','String','FinalFrame [g]',...
'Position',[xP,yP,bW,bH],...
'Callback',@finalbutton_callback);
%section3
bW=bW*1.5;
% htextone
xP = xPi-(sW*3)-bW;
yP = yPi;
uicontrol('Style','text','String','Choose Scene',...
'Position',[xP,yP,bW,bH./2]);
% htextone
xP = xP-(sW)-bW;
uicontrol('Style','text','String','Channel View',...
'Position',[xP,yP,bW,bH./2]);
% choose segment channel
xP = xP-(sW)-bW-bW./2;
uicontrol('Style','text','String','Segmentation View',...
'Position',[xP,yP,bW+bW./2,bH./2]);
%section4 (dropdown "popupmenus")
% hpopupSceneList
xP = xPi-(sW*3)-bW;
yP = yP-(sW*2);
uicontrol('Style','popupmenu',...
'String',SceneList',...
'Position',[xP,yP,bW,bH./2],...
'Callback',@popup_menu_Callback);
% hpopupChannelList
xP = xP-(sW)-bW;
uicontrol('Style','popupmenu',...
'String',channelList',...
'Position',[xP,yP,bW,bH./2],...
'Callback',@popup_menu_Callback_channels);
% hpopupChannelList
xP = xP-(sW)-bW-bW./2;
uicontrol('Style','popupmenu',...
'String',segmentListDisp',...
'Position',[xP,yP,bW+bW./2,bH./2],...
'Callback',@popup_menu_Callback_segment);
%final Save button
% hFirstFrame
xP = xPi;
yP = yPi-bH-bH-bH-bH-(sW*3);
uicontrol('Style','pushbutton',...
'String','saveSomethingCallback',...
'Position',[xP,yP,bW.*2,bH.*2],...
'Callback',@saveSomethingCallback);
f.Visible = 'on' ;
% f.Units = 'normalized';
for i = 1:length(f.Children)
hhh = f.Children(i);
hhh.Units = 'normalized';
hhh.FontSize = 8;
end
channelimglength = 9;
xi = 0.02;
yi = 0.025;
w = 0.15;
h = 0.28;
xspf = 0.1; %xspacefactor
yspf = 0.1;
dimm = [3 3];
xvc=[];
yvc=[];
for i = 1:dimm(1)
xvi = [];
yvi = [];
for j = 1:dimm(2)
xv = xi + (xspf*w)*(j-1) + (w*(j-1));
xvi = horzcat(xvi,xv);
yv = yi + (yspf*h)*(i-1) + (h*(i-1));
yvi = horzcat(yvi,yv);
end
xvc = horzcat(xvc,xvi);
yvc = horzcat(yvi,yvc);
end
% x = [xi xi+w+(xspf*w) xi+(w+(xspf*w)).*2 xi xi+w+(xspf*w) xi+(w+(xspf*w)).*2 xi xi+w+(xspf*w) xi+(w+(xspf*w)).*2];
% y = fliplr([yi yi yi yi+h+(yspf*w) yi+h+(yspf*w) yi+h+(yspf*w) yi+(w+(yspf*w)).*2 yi+(w+(yspf*w)).*2 yi+(w+(yspf*w)).*2]);
x=xvc;
y=yvc;
for i=1:dimm(1)*dimm(2)
ax= axes();
ax.Position = [x(i) y(i) w h];
ax.Units = 'inches';
pos = ax.Position;
%make them square
if pos(4)>pos(3)
pos(4) = pos(3);
else
pos(3) = pos(4);
end
ax.Position = pos;
ax.Units = 'normalized';
ax.XTick = [];
ax.YTick = [];
subaxes(i) = ax;
end
xi = 0.65;
yi = 0.025;
w = 0.15;
h = 0.28;
xspf = 0.1; %xspacefactor
yspf = 0.1;
dimm = [2 2];
xvc=[];
yvc=[];
for i = 1:dimm(1)
xvi = [];
yvi = [];
for j = 1:dimm(2)
xv = xi + (xspf*w)*(j-1) + (w*(j-1));
xvi = horzcat(xvi,xv);
yv = yi + (yspf*h)*(i-1) + (h*(i-1));
yvi = horzcat(yvi,yv);
end
xvc = horzcat(xvc,xvi);
yvc = horzcat(yvc,yvi);
end
x = xvc;
y = yvc;
for i=1:dimm(1)*dimm(2)
ax= axes();
ax.Position = [x(i) y(i) w h];
ax.Units = 'inches';
pos = ax.Position;
%make them square
if pos(4)>pos(3)
pos(4) = pos(3);
else
pos(3) = pos(4);
end
ax.Position = pos;
ax.Units = 'normalized';
ax.XTick = [];
ax.YTick = [];
subaxestwo(i) = ax;
end
%define parameter structure and default parameter values
pStruct = defaultpStructFunc(segInstructList);
pStruct = loadSegmentParameters(pStruct,FileName,exportdir); %loads saved value of pStruct
f.Units='normalized';
f.Position =[0.1,0.2,0.8,0.7];
set(f,'KeyPressFcn',@keypress);
end
function pStruct = defaultpStructFunc(segInstructList)
pStruct = struct();
parameterDefaults.background = [150 1 2 0.5 1 2];
parameterDefaults.nucleus = [30 1 2 0.5 1 2];
parameterDefaults.cell = [40 1 2 0.5 10 10];
parameterStrings = {'nucDiameter','threshFactor','sigmaScaledToParticle','metthresh','percentSmoothed','denoise'};
for p = 1:length(parameterStrings)
pString = char(parameterStrings{p});
for c = 1:length(segInstructList)
cstr = char(segInstructList{c});
cString = alterChanName(cstr);
pd = parameterDefaults.(cString);
pStruct.(cString).(pString) = pd(p);
end
end
end
function pStruct = loadSegmentParameters(pStruct,datename,exportdir)
cd(exportdir)
filename = strcat('*',datename,'*segmentParameters*');
filelist = dir(filename);
if ~isempty(filelist)
loadname = char((filelist.name));
A = load(loadname); %load pstruct values
pStruct = A.pStruct;
else
disp('no saved parameters')
end
end
function saveSomethingCallback(~,~)
global exportdir OGExpDate pStruct
cd(exportdir)
filename = strcat('*',OGExpDate,'*metaData*')
filelist = dir(filename)
savenamebase = char((filelist.name));
savename = strcat(OGExpDate,'-segmentParameters.mat');
save(savename,'pStruct');
end
function updateSliders
global pStruct ImageDetails sliderOne sliderOneTxt
sliderx = 0.72;
sliderw = 0.1;
sliderh = 0.02;
slidertextw = 0.1;
sliderspace = 0.1;
channel = ImageDetails.segInstruct;
%nucDiameter
fnames = fieldnames(pStruct.(channel));
sliderspacing = linspace(0.8,0.7,length(fnames));
for cyc = 1:length(fnames)
str = fnames{cyc};
if strcmp(str,'nucDiameter')
minz = 1;
maxz = 400;
ssa = 1/5;%sliderStepAdjust
elseif strcmp(str,'threshFactor')
minz = 0.4;
maxz = 3;
ssa = 20;
elseif strcmp(str,'sigmaScaledToParticle')
minz = 1;
maxz = 40;
ssa = 1;
elseif strcmp(str,'metthresh')
minz = 0;
maxz = 1;
ssa = 20;
elseif strcmp(str,'percentSmoothed')
minz = 1;
maxz = 100;
ssa = 1/2.5;
elseif strcmp(str,'denoise')
minz = 2;
maxz = 40;
ssa = 1/5;
else
disp('parameter NOT CURRENTLY DEFINED')
if sum(strcmp(fnames,'metthresh'))<1
str = 'metthresh';
minz = 0;
maxz = 1;
ssa = 20;
pStruct.(channel).(str) = 0.1;
end
end
val.(str) = pStruct.(channel).(str);
slidery = sliderspacing(cyc);
sliderOne.(str) = uicontrol('Style', 'slider','String',str,'Min',minz,'Max',maxz,'SliderStep',[1 1]./((maxz-minz).*ssa),'Value',val.(str),'Position', [1 1 1 1],...
'Callback', @sliderOneAdjust);
sliderOne.(str).Units='normalized';
sliderOne.(str).Position = [sliderx slidery sliderw sliderh];
sliderOneTxt.(str) = uicontrol('Style','text','Units','Normalized','Position',[1 1 1 1],'String',strcat(str,'=',num2str((val.(str)))));
sliderOneTxt.(str).Units= 'Normalized';
sliderOneTxt.(str).Position = [sliderx-sliderspace slidery slidertextw sliderh];
end
end
function channelinputs =channelregexpmaker(channelstoinput)
channelinputs = '(';
for i=1:length(channelstoinput) % creates a string of from '(c1|c2|c3|c4)' for regexp functions
if i ==1
channelinputs = strcat(channelinputs,channelstoinput{i});
elseif i < length(channelstoinput)
channelinputs = strcat(channelinputs,'|',channelstoinput{i});
else
channelinputs = strcat(channelinputs,'|',channelstoinput{i},')');
end
end
end
function channelinputs =channelregexpmakerUnderscore(channelstoinput)
channelinputs = '(';
for i=1:length(channelstoinput) % creates a string of from '(c1|c2|c3|c4)' for regexp functions
if i ==1
channelinputs = strcat(channelinputs,channelstoinput{i},'_');
elseif i < length(channelstoinput)
channelinputs = strcat(channelinputs,'|',channelstoinput{i},'_');
else
channelinputs = strcat(channelinputs,'|',channelstoinput{i},'_)');
end
end
end
function sliderOneAdjust(source,~)
global pStruct ImageDetails sliderOneTxt
channel = ImageDetails.segInstruct;
str = source.String;
% threshinput.(str) =source.Value;
% zerostrel = round(source.Value);
if strcmpi(str,'threshFactor')
valupdate = source.Value;
elseif strcmpi(str,'metthresh')
valupdate = source.Value;
else
valupdate = round(source.Value);
end
source.Value = valupdate;
pStruct.(channel).(str) = valupdate;
disp(valupdate)
source.Visible = 'off';
sliderOneTxt.(str).String = 'waiting...';
pause(0.001);
setSceneAndTime
disp('done')
source.Visible = 'on';
sliderOneTxt.(str).String = strcat(str,'=',num2str(pStruct.(channel).(str)));
end
function plotTestOut(testOut,channel)
global subaxestwo
if strcmp(channel,'mKate')
stringsToTest = {'rawMinusLPScaled','Inew','gradmag2','Ieg'};
else
% stringsToTest = {'rawMinusLPScaled','Ih','Ihcd','Shapes'};
stringsToTest = {'rawMinusLPScaled','Inew','gradmag2','Ieg'};
end
for i = 1:length(subaxestwo)
axes(subaxestwo(i))
str = stringsToTest{i};
img = testOut.(str);
imagesc(img);t=title(str);
t.FontSize=8;
h=gca;
h.XTick=[];
h.YTick=[];
end
% testOut.img = img;
% testOut.imgRawDenoised = imgRawDenoised;
% testOut.imgLowPass = imgLowPass;
% testOut.rawMinusLP = rawMinusLP;
% testOut.rawMinusLPScaled = rawMinusLPScaled;
% testOut.Ih = Ih;
% testOut.L = zeros[512 512];
%
end
function [IfFinal,testOut] = segmentationNucleus(FinalImage,segmentPath,nucleus_seg,nucleusFileName,pStruct)
testOut = struct();
frames = 1;
img = FinalImage(:,:,frames);
% frames=1;
[~,testOut] = segmentNuclei(img,nucleus_seg,pStruct,frames);
IfFinal = false(size(FinalImage));
for frames = 1:size(FinalImage,3)
img = FinalImage(:,:,frames);
[If,~] = segmentNuclei(img,nucleus_seg,pStruct,frames);
IfFinal(:,:,frames)=If;
end
%save here if running actual segmentation
end
function [IfFinal,testOut] = segmentationImageBackground(FinalImage,segmentPath,background_seg,backgroundFileName,pStruct)
testOut = struct();
frames = 1;
img = FinalImage(:,:,frames);
tic
[~,testOut] = segmentCellBackgroundOLDGREAT(img,background_seg,pStruct,frames);
toc
tic
[~,testOut] = segmentCellBackground(img,background_seg,pStruct,frames);
toc
IfFinal = false(size(FinalImage));
for frames = 1:size(FinalImage,3)
img = FinalImage(:,:,frames);
[If,~] = segmentCellBackground(img,background_seg,pStruct,frames);
IfFinal(:,:,frames)=If;
end
%save here if running actual segmentation
disp('done')
% parameters
end
function [IfFinal,testOut] = segmentationDIC(FinalImage,subdirname,scenename,filename,channel)
global pStruct foldernameglobal
cd(subdirname)
foldername = foldernameglobal;
% parameters
nucDiameter = pStruct.(channel).nucDiameter;
threshFactor = pStruct.(channel).threshFactor;
sigmaScaledToParticle = pStruct.(channel).sigmaScaledToParticle;
kernelgsize = nucDiameter; %set kernelgsize to diameter of nuclei at least
sigma = nucDiameter./sigmaScaledToParticle; %make the sigma about 1/5th of kernelgsize
finalerode=2;
% prepareCcodeForAnisotropicDiffusionDenoising(denoisepath)
%start
for frames = 1:size(FinalImage,3)
%Smooth Image using Anisotropic Diffusion
% Options.Scheme : The numerical diffusion scheme used
% 'R', Rotation Invariant, Standard Discretization
% (implicit) 5x5 kernel (Default)
% 'O', Optimized Derivative Kernels
% 'I', Implicit Discretization (only works in 2D)
% 'S', Standard Discretization
% 'N', Non-negativity Discretization
% Options.T : The total diffusion time (default 5)
% Options.dt : Diffusion time stepsize, in case of scheme H,R or I
% defaults to 1, in case of scheme S or N defaults to
% 0.15.
% Options.sigma : Sigma of gaussian smoothing before calculation of the
% image Hessian, default 1.
% Options.rho : Rho gives the sigma of the Gaussian smoothing of the
% Hessian, default 1.
% Options.verbose : Show information about the filtering, values :
% 'none', 'iter' (default) , 'full'
% Options.eigenmode : There are many different equations to make an diffusion tensor,
% this value (only 3D) selects one.
% 0 (default) : Weickerts equation, line like kernel
% 1 : Weickerts equation, plane like kernel
% 2 : Edge enhancing diffusion (EED)
% 3 : Coherence-enhancing diffusion (CED)
% 4 : Hybrid Diffusion With Continuous Switch (HDCS)
img = FinalImage(:,:,frames);
imgRaw = gaussianBlurz(single(img),ceil(sigma./10),ceil(kernelgsize./10));
imgW = wiener2(img,[1 20]);
imgWW = wiener2(imgW,[20 1]);
imgWWW = wiener2(imgWW,[5 5]);
imgRawDenoised = imgWWW;
denoiseVec = single(reshape(imgRawDenoised,size(imgRawDenoised,1)^2,1));
highpoints = prctile(denoiseVec,95);
imgRawDenoised(imgRawDenoised>highpoints) = highpoints;
% Options.T = 5;
% Options.dt = 1;
% Options.Scheme = 'R';
% Options.rho = 20;
% Options.sigma = 20;
% Options.verbose = 'none';ii
% % imgRawDenoised = CoherenceFilter(imgRaw, Options);
% % imgRawDenoised = imgRaw;
%Based on algorithm of Fast and accurate automated cell boundary determination for fluorescence microscopy by Arce et al (2013)
%LOW PASS FILTER THE IMAGE (scale the gaussian filter to diameter of
%nuclei -- diameter of nuclei is about 50 to 60))
imgLowPass = gaussianBlurz(single(imgRawDenoised),sigma,kernelgsize);
rawMinusLP = single(imgRawDenoised) -single(imgLowPass);%%%%%%% key step!
rawMinusLPvec = reshape(rawMinusLP,size(rawMinusLP,1)^2,1);
globalMinimaValues = prctile(rawMinusLPvec,0.01);
globalMinimaIndices = find(rawMinusLP < globalMinimaValues);
LPscalingFactor = imgRawDenoised(globalMinimaIndices)./imgLowPass(globalMinimaIndices);
imgLPScaled = imgLowPass.*nanmedian(LPscalingFactor);
rawMinusLPScaled = single(imgRawDenoised) - single(imgLPScaled);
%determine the threshold by looking for minima in log-scaled histogram
%of pixels from rawMinusLPScaled
rawMinusLPScaledContrasted = imadjust(uint16(rawMinusLPScaled));
vecOG = single(reshape(rawMinusLPScaledContrasted,size(rawMinusLPScaledContrasted,1)^2,1));
logvecpre = vecOG; logvecpre(logvecpre==0)=[];
logvec = log10(logvecpre);
vec = logvec;
[numbers,bincenters] = hist(vec,prctile(vec,1):(prctile(vec,99)-prctile(vec,1))/1000:max(vec));
numbersone = medfilt1(numbers, 10); %smooths curve
numberstwo = medfilt1(numbersone, 100); %smooths curve
fraction = numberstwo./sum(numberstwo);
mf = max(fraction);
%%%%%%%%%%%%%%%%%%%% Important parameters for finding minima of
%%%%%%%%%%%%%%%%%%%% histogram
left=0.5*mf;
slopedown=0.4*mf;
%%%%%%%%%%%%%%%%%%%%%
leftedge = find(fraction > left,1,'first');
insideslopedown = find(fraction(leftedge:end) < slopedown,1,'first');
threshLocation = bincenters(leftedge+insideslopedown-1);
subtractionThreshold = threshLocation;
if size(subtractionThreshold,1)==size(subtractionThreshold,2)
else
subtractionThreshold = mean(threshLocation);
end
subtractionThresholdScaled = (10.^subtractionThreshold).*threshFactor;
subtracted = single(rawMinusLPScaledContrasted)-subtractionThresholdScaled;
subzero = (subtracted<0);
Ih = ~subzero;
Im = Ih;
If =Im;
I = -1.*rawMinusLPScaled;
waterBoundary = Ih;
%gradmag
hy = fspecial('sobel');
hx = hy';
Iy = imfilter(single(I), hy, 'replicate');
Ix = imfilter(single(I), hx, 'replicate');
gradmag = sqrt(Ix.^2 + Iy.^2);
%Smoothing
% I = Ih;
width = round(nucDiameter./4);
se = strel('disk', width);
Io = imopen(I, se);
Ie = imerode(Io, se);
Ieg = gaussianBlurz(Ie,sigma./2,kernelgsize);
% width = round(nucDiameter./10);
% Ime = imerode(Ihcf,strel('disk',width));
% Imeo = imopen(Ime,strel('disk',width));
% Ieg(~Imeo)=0;
fgm = imregionalmax(Ieg);
width = round(nucDiameter./20);
fgm4 = imdilate(fgm,strel('disk',width));
% fgm4 =fgm;
bw = Im;
D = bwdist(bw);
DL = watershed(D,4);
bgm = DL == 0;
gradmag2 = imimposemin(gradmag, bgm | fgm4);
L = watershed(gradmag2,8);
L(waterBoundary<1) = 0;
% If = L>1;
time = tsn{frames};
tim = time(2:end);
IfFinal(:,:,frames)=If;
if frames==1
testOut.img = img;
testOut.I = -1.*rawMinusLPScaled;
testOut.imgRawDenoised = imgRawDenoised;
testOut.imgLowPass = imgLowPass;
testOut.rawMinusLP = rawMinusLP;
testOut.rawMinusLPScaled = rawMinusLPScaled;
testOut.Ih = Ih;
% testOut.Ihc = Ihc;
testOut.Im = Im;
% testOut.Ihcd = Ihcd;
testOut.L = zeros([512 512]);
% testOut.gradmag = gradmag;
testOut.gradmag = zeros(size(img));
% testOut.gradmag2 = gradmag2;
testOut.gradmag2 = zeros(size(img));
% testOut.Ie = Ie;
testOut.Ie = zeros(size(img));
% testOut.fgm4 = fgm4;
testOut.fgm4 = zeros(size(img));
% testOut.Ieg = Ieg;
testOut.Ieg = zeros(size(img));
testOut.Shapes = zeros(size(img));
% testOut.waterBoundary = waterBoundary;
end
end
stophere=1;
end
function bw = gaussianBlurz(im,sigma,kernelgsize,varargin)
filtersize = [kernelgsize kernelgsize];
kernelg = fspecial('gaussian',filtersize,sigma);
gFrame = imfilter(im,kernelg,'repl');
if ~isempty(varargin)
bw=gFrame.*uint16(varargin{1}>0);
else
bw=gFrame;
end
end
function keypress(fig_obj,~)
global ImageDetails displaycomments
key = get(fig_obj,'CurrentKey');
switch key
case '1'
ImageDetails.Channel = 'EGFP';
setSceneAndTime
case '2'
ImageDetails.Channel = '_Hoechst';
setSceneAndTime
case '3'
ImageDetails.Channel = 'mKate';
setSceneAndTime
case '4'
ImageDetails.Channel = 'DIC';
setSceneAndTime
case '5'
ImageDetails.Channel = 'BKGbinary';
setSceneAndTime
case '6'
ImageDetails.Channel = 'overlay';
setSceneAndTime
case 'q'
prevscenebutton_Callback([],[])
case 'w'
nextscenebutton_Callback([],[])
case 'a'
prevbutton_callback([],[])
case 'f'
nextbutton_callback([],[])
case 'd'
deletebutton_Callback([],[]);
case 't'
trackbutton_Callback([],[]);
case 'e'
eliminatebutton_Callback([],[]);
case 'v'
addareabutton_Callback([],[]);
case 'r'
linkCells_Callback([],[]);
case 'm'
displayTrackingButton_Callback([],[])
case 'g'
finalbutton_callback([],[])
case 'z'
firstbutton_callback([],[])
case 's'
saveTrackingFileAs_callback([],[])
case 'l'
loadTrackingFile_callback([],[])
case 'p'
Plot_callback([],[])
case 'o'
labelCells;
case 'u'
% if displaycomments==1
% displaycomments=0;
% else
displaycomments=1;
xy = getxy([],[]);
% end
case 'c'
contrast_Callback([],[])
case 'k'
comment_Callback([],[])
case 'j'
comment_CallbackJ([],[])
case 'n'
PlotCFPnorm_callback([],[])
case 'b'
PlotCFPnotnorm_callback([],[])
case '0'
displaycomments=1;
xy = getxy([],[]);
[~,comments,commentpos,cellidx]=updatecomments(xy);
setcommentsTracking(comments,commentpos)
dispxy(xy)
end
end
%choose frames
function nextbutton_callback(~,~)
global framesForDir ImageDetails
if isempty(ImageDetails.Frame)
ImageDetails.Frame = framesForDir{1};
end
Idx = strcmp(ImageDetails.Frame,framesForDir);
idx = find(Idx == 1);
if idx == length(framesForDir)
else
idx = idx + 1;
end
ImageDetails.Frame = framesForDir{idx};
setSceneAndTime
end
function prevbutton_callback(~,~)
global framesForDir ImageDetails
if isempty(ImageDetails.Frame)
ImageDetails.Frame = framesForDir{1};
end
Idx = strcmp(ImageDetails.Frame,framesForDir);
idx = find(Idx == 1);
if idx == 1
else
idx = idx - 1;
end
ImageDetails.Frame = framesForDir{idx};
setSceneAndTime
end
function finalbutton_callback(~,~)
global framesForDir ImageDetails
idx = length(framesForDir);
ImageDetails.Frame = framesForDir{idx};
setSceneAndTime
end
function firstbutton_callback(~,~)
global framesForDir ImageDetails
idx = 1;
ImageDetails.Frame = framesForDir{idx};
setSceneAndTime
end
function gotobutton_callback(~,~)
global framesForDir ImageDetails
if isempty(ImageDetails.Frame)
ImageDetails.Frame = framesForDir{1};
end
prompt = {'Go to which frame'};
dlg_title = 'Go to frame...';
idx = str2num(cell2mat(inputdlg(prompt,dlg_title)));
ImageDetails.Frame = framesForDir{idx};
setSceneAndTime
end
%choose scenes
function nextscenebutton_Callback(~,~)
global ImageDetails Tracked SceneList
Tracked=[];