forked from clementvulin/ColoniesTimeLapseAnalysis
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathColoniesTimeLapseAnalysis.m
More file actions
1791 lines (1557 loc) · 67.4 KB
/
ColoniesTimeLapseAnalysis.m
File metadata and controls
1791 lines (1557 loc) · 67.4 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
% to do
% in refresh, do not reload when i is the same
% user input filename
% user input threshold vector
% batch mode for several analysis
% scale for petri dish?
% analyse all?
% calculate lag time?
% put tic toc message in pluggin + took toc time
% add image in code
%
%% initiating GUI
function varargout = ColoniesTimeLapseAnalysis(varargin)
% COLONIESTIMELAPSEANALYSIS MATLAB code for ColoniesTimeLapseAnalysis.fig
% COLONIESTIMELAPSEANALYSIS, by itself, creates a new COLONIESTIMELAPSEANALYSIS or raises the existing
% singleton*.
%
% H = COLONIESTIMELAPSEANALYSIS returns the handle to a new COLONIESTIMELAPSEANALYSIS or the handle to
% the existing singleton*.
%
% COLONIESTIMELAPSEANALYSIS('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in COLONIESTIMELAPSEANALYSIS.M with the given input arguments.
%
% COLONIESTIMELAPSEANALYSIS('Property','Value',...) creates a new COLONIESTIMELAPSEANALYSIS or raises
% the existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before ColoniesTimeLapseAnalysis_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to ColoniesTimeLapseAnalysis_OpeningFcn via varargin.
%
% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one
% instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES
% Edit the above text to modify the response to help ColoniesTimeLapseAnalysis
% Last Modified by GUIDE v2.5 15-Jan-2017 15:40:22
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @ColoniesTimeLapseAnalysis_OpeningFcn, ...
'gui_OutputFcn', @ColoniesTimeLapseAnalysis_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT
% --- Executes just before ColoniesTimeLapseAnalysis is made visible.
end
function ColoniesTimeLapseAnalysis_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin command line arguments to ColoniesTimeLapseAnalysis (see VARARGIN)
% Choose default command line output for ColoniesTimeLapseAnalysis
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
initialize_gui(hObject, handles, false);
% UIWAIT makes ColoniesTimeLapseAnalysis wait for user response (see UIRESUME)
% uiwait(handles.figure1);
% --- Outputs from this function are returned to the command line.
end
function varargout = ColoniesTimeLapseAnalysis_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Get default command line output from handles structure
varargout{1} = handles.output;
% --- Executes during object creation, after setting all properties.
end
function handles=initialize_gui(fig_handle, handles, isreset)
% If the metricdata field is present and the setNum flag is false, it means
% we are we are just re-initializing a GUI by calling it from the cmd line
% while it is up. So, bail out as we dont want to setNum the data.
if isfield(handles, 'metricdata') && ~isreset
return;
end
%image analysis
handles.minRadN = 20;
handles.maxRadN = 60;
set(handles.minRad, 'String', handles.minRadN);
set(handles.maxRad, 'String', handles.maxRadN);
handles.sensitivityN = 0.82;
handles.sauvolarange=[100 100];% this is used for autothresholding of image
%counts and radii
handles.counts=cell(4,4);
handles.centers = [];
handles.radii = [];
handles.centersBack = [];
handles.radiiBack = [];
%file and folder handling
handles.dir='/Users/vulincle/Desktop/test_timeLapse/jpg';
handles.i = 1;
handles.l = []; %will contain a list of files with filename
%handles.filename='IMG_'; %typical filename before numbers
handles.filextension='.JPG';
% dust handling (not usefull for colony analysis)
handles.rgbAVG=[];
handles.numImgAVG = 30;
handles.centersDust = [];
handles.radiiDust = [];
handles.OnlyCenterTick=0;
handles.apR=1; %appearing radius for cells
set(handles.NumCells, 'String', 0);
set(handles.timeRemain, 'String', '');
%local empty variables will contain data
handles.rgb=[];
handles.im=[];
handles.RadMean=[];
handles.RadMean2=[];
handles.Rad=[];
%for timelapse analysis
handles.Zonesize=1.2;
handles.percsizeMean=0.01;% total image area to define the zero
handles.Tresh=3; %Threshold under which there is no colony (in fold of min)
handles.Numtresh=5;%number of values needed to call threshold reached
handles.tres=128; % # of grid points for theta coordinate (change to needed binning)
handles.showplot=0; %if true, shows the graphs of analysis in userwindow
%image handling
handles.panButton=0;
% Update handles structure
guidata(handles.figure1, handles);
end %initiate all parameters
%% naviguate images
function chngdir_Callback(hObject, eventdata, handles)
% hObject handle to chngdir (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
%ask user for dir
handles.dir=uigetdir(handles.dir,'please select the directory with the files to correct');
if handles.dir==0; return; end; %user cancelled
set(handles.currentdir, 'String', handles.dir);
guidata(handles.figure1, handles);
chngDir(handles.figure1, handles.dir,handles);
%length(handles.l)
end
function errorloading=chngDir(figure1, directory, handles) %will return 1 if loading was correct
%getting file list
errorloading=1;
handles.l=dir([directory, '/', '*',handles.filextension]); %lists all files with filextension
%removing the possible hidden files or subfolders. They start with "."
for h=1:size(handles.l,1)
keep(h)=(handles.l(h).name(1)~='.');
end
handles.l=handles.l(keep);
if isempty(handles.l)
errordlg(['Did not find any ' handles.filextension ' images in folder' directory '. If you are working with other images types, please consider editing handles.filextension.'],'Error');
errorloading=0;
return
end
%loading previously saved data if existant
% if ~isempty(dir([directory, '/', '*','all','*'])); %found a file countaing "all"
% try
% files=dir([directory, '/', '*','all','*']);
% fileAll=load([directory,'/',files(end).name]); %this contains, counts, i, Rad, RadMean, dir, minRad, maxRad and sensitivity
% handles.counts=fileAll.counts;
% handles.oldi=fileAll.i;
% handles.Rad=fileAll.Rad;
% handles.RadMean=fileAll.RadMean;
% handles.minRad=fileAll.minRad;
% handles.maxRad=fileAll.maxRad;
% handles.sensitivity=fileAll.sensitivity;
% catch
% disp('did not find all files');
% handles.counts=cell(length(handles.l),2); %creating empty cell with the nb of pictures
% errorloading=0;
% handles.i=1;
% end
% set(handles.UserMess, 'String', 'found previous analysis, loaded it into Matlab');
% elseif
if size(dir([handles.dir, '/', '*','_all.mat']),1) %there is a _all.mat file
fileSaved=dir([handles.dir, '/', '*','_all.mat']);
fileload=load([handles.dir, '/', fileSaved(1).name]); %nb: here, if there are several matching files, Matlab takes the first one
handles.counts=fileload.counts;
handles.i=fileload.i;
handles.maxRad=fileload.maxRad;
handles.minRad=fileload.minRad;
handles.Rad=fileload.Rad;
handles.RadMean=fileload.RadMean;
handles.RadMean2=fileload.RadMean2;
handles.sensitivity=fileload.sensitivity;
set(handles.UserMess, 'String', ['found ',fileSaved(1).name ,', loaded it into Matlab']);
elseif exist ([handles.dir '/sidesave.mat'], 'file')&& exist ([handles.dir '/stoped_at.mat'], 'file') %check for an older saved analysis
handles.countsload=load([handles.dir '/sidesave.mat']); %this file was produced when saving
handles.oldiload=load([handles.dir '/stoped_at.mat']); %this file was produced when saving
handles.counts=handles.countsload.counts; %because load gives a struct object
handles.oldi=handles.oldiload.i;
set(handles.UserMess, 'String', 'found previous analysis, loaded it into Matlab');
elseif exist([handles.dir '/counts.mat'], 'file')
handles.countsload=load ([handles.dir '/counts.mat']); %this file was produced when analysing
handles.counts=handles.countsload.counts; %because load gives a struct object
handles.oldi=1; %start from the start!
else %nothing found
handles.counts=cell(length(handles.l),2); %creating empty cell with the nb of pictures
errorloading=0;
handles.i=1;
end
%handles.rgb = imread([handles.dir, '/',handles.l(handles.i).name]); %load pic
% Update handles structure
guidata(figure1, handles);
refresh(handles,0);
end % --- Executes on button press in chngdir.
function next_Callback(hObject, eventdata, handles)
% hObject handle to next (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% a=handles.i;
if handles.i<length(handles.l)
handles.counts{handles.i,1}=handles.centers;
handles.counts{handles.i,2}=handles.radii;
handles.i=handles.i+1;
guidata(hObject,handles)% Update handles structure
refresh(handles,0);
else
errordlg('No image after this one','Error');
end
end % --- Executes on button press in next.
function previous_Callback(hObject, eventdata, handles)
% hObject handle to next (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
if handles.i>1
handles.counts{handles.i,1}=handles.centers;
handles.counts{handles.i,2}=handles.radii;
handles.i=handles.i-1;
guidata(hObject,handles)% Update handles structure
refresh(handles,0);
else
errordlg('No image before this one','Error');
end
end % --- Executes on button press in previous.
function NumSlice_Callback(hObject, eventdata, handles)
% hObject handle to NumSlice (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of NumSlice as text
% str2double(get(hObject,'String')) returns contents of NumSlice as a double
i = str2double(get(hObject, 'String')); %getting value
if isnan(i) %if not a number, error
set(hObject, 'String', 0);
errordlg('Input must be a number','Error');
end
if i>0 && i<length(handles.l)+1 %checking it is inside range
handles.i = i;
guidata(hObject,handles)
refresh(handles,0);
else
errordlg('Input number outside of range','Error');
end
end % --- Executes on button press in AddCells.
function NumSlice_CreateFcn(hObject, eventdata, handles)
% hObject handle to NumSlice (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
end % --- Executes during object creation, after setting all properties.
function setNum_Callback(hObject, eventdata, handles) %#ok<*INUSL>
% hObject handle to setNum (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
%initialize_gui(gcbf, handles, true);
if sum(size(handles.l))==0; %the list doesn't exist
errordlg('please load a image series')
return
end
%in the end, this is just a refresh function:
refresh(handles,0);
end % --- Executes on button press in setNum.
%% modify images
function AddCells_Callback(hObject, eventdata, handles)
if sum(size(handles.l))==0; %the list doesn't exist
errordlg('please load a image series')
return
end
handles.centersBack=handles.centers; %saving for undo purpose
handles.radiiBack=handles.radii; %saving for undo purpose
if handles.OnlyCenterTick %this means user is only interreted in centers
set(handles.UserMess, 'String', 'click on image for new circle center(s), press retur key ');
[X1, Y1] = ginput;
X1=X1; Y1=Y1;
r=ones(length(X1),1); %the radius is selected to be 1
else %in the case where user wants to use radius values
% instructions to users
set(handles.UserMess, 'String', 'click on image for a new colony, drag to radius, then click again');
%get colony center
[X1, Y1] = ginput(1);
hold on;
h = plot(X1, Y1, 'r');
%get radius from a sencon click
set(gcf, 'WindowButtonMotionFcn', {@mousemove, h, [X1 Y1]}); %to have an updating circle
k = waitforbuttonpress; %#ok<NASGU>
set(gcf, 'WindowButtonMotionFcn', ''); %unlock the graph
r = norm([h.XData(1) - X1 h.YData(2) - Y1]); %circle coordinates are in h object
end
%add cells
if size(handles.centers,1)>=1 %add to existing list
a=[handles.centers(:,1);X1] ;%to check
b=[handles.centers(:,2);Y1] ;%to check
handles.centers=[a b];
handles.radii=[handles.radii;r];
else %or to empty matrix
handles.centers=[X1,Y1];
handles.radii=r;
end
% Update handles structure
handles.counts{handles.i,1}=handles.centers;
handles.counts{handles.i,2}=handles.radii;
guidata(hObject, handles);
%refresh Graph
refresh(handles,1);
end %OK
function mousemove(object, eventdata, h, bp)
%from http://stackoverflow.com/questions/13840777/select-a-roi-circle-and-square-in-matlab-in-order-to-aply-a-filter
cp = get(gca, 'CurrentPoint');
r = norm([cp(1,1) - bp(1) cp(1,2) - bp(2)]);
theta = 0:.1:2*pi;
xc = r*cos(theta)+bp(1);
yc = r*sin(theta)+bp(2);
set(h, 'XData', xc);
set(h, 'YData', yc);
end % --- This function to refresh upon mouse move
function ClearZone_Callback(hObject, eventdata, handles)
% hObject handle to ClearZone (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
if sum(size(handles.l))==0; %the list doesn't exist
errordlg('please load a image series')
return
end
handles.centersBack=handles.centers; %saving for undo purpose
handles.radiiBack=handles.radii; %saving for undo purpose
set(handles.UserMess, 'String', 'choose zone to remove cells');
[~,xi,yi]=roipoly(); %user inputs a polygon
%remove for current frame
in=inpolygon(handles.centers(:,1),handles.centers(:,2),xi,yi); %all cells in polygon
handles.centers=handles.centers(in==0,:); %remove from centers
handles.radii=handles.radii(in==0); %remove from radii
% Update handles structure
handles.counts{handles.i,1}=handles.centers;
handles.counts{handles.i,2}=handles.radii;
guidata(hObject, handles);
refresh(handles,1);
end % --- Executes on button press in ClearZone.
function ClearRecZone_Callback(hObject, eventdata, handles)
% hObject handle to ClearZone (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
if sum(size(handles.l))==0; %the list doesn't exist
errordlg('please load a image series')
return
end
handles.centersBack=handles.centers; %saving for undo purpose
handles.radiiBack=handles.radii; %saving for undo purpose
set(handles.UserMess, 'String', 'choose zone to remove cells');
[~,xi,yi]=roipoly(); %user inputs a polygon
%remove for current frame
in=inpolygon(handles.centers(:,1),handles.centers(:,2),xi,yi); %all cells in polygon
handles.centers=handles.centers(in==1,:); %remove from centers
handles.radii=handles.radii(in==1); %remove from radii
% Update handles structure
handles.counts{handles.i,1}=handles.centers;
handles.counts{handles.i,2}=handles.radii;
guidata(hObject, handles);
refresh(handles,1);
end % --- Executes on button press in ClearRecZone.
function AddDust_Callback(hObject, eventdata, handles)
% hObject handle to AddCells (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
if sum(size(handles.l))==0; %the list doesn't exist
errordlg('please load a image series')
return
end
%create a average image for dust (15 images)
set(handles.UserMess, 'String', 'averaging images...');
rgbAVG=handles.rgb*0;
for i=handles.i:handles.i+handles.numImgAVG-1
%look for file
fil=[handles.dir, '/', ...
handles.filename,num2str(i),handles.filextension]; %this is file name with dir
fil2=[handles.dir, '/', ...
handles.filename2,num2str(i,['%0',num2str(handles.digNumbers),...
'd']),handles.filextension]; %two alternative names
if ~exist(fil,'file') && ~exist(fil2,'file')
disp (['could not find file ',fil, ' or ', filename2,num2str(i,['%0',...
num2str(digNumbers),'d']),filextension]) %didn't find file
else
if ~exist(fil,'file') %not this file, then it is the other
fil=fil2;
end
rgb = imread(fil); %load pic
rgbAVG=rgbAVG+rgb/handles.numImgAVG;%imadjust(handles.rgb); %this is an autocontrast
end
end
%handles.rgbAVG=imadjust(rgbAVG);
imshow(handles.rgbAVG,'InitialMagnification', 25)
viscircles(handles.centersDust,...
handles.radiiDust*handles.apR,...
'Color','b');
% Update handles structure
guidata(handles.figure1, handles);
% instructions to users
set(handles.UserMess, 'String', 'click on image on the dust, then press enter');
[x,y] = ginput; %user inputs new cells by clicking
%add cells
if size(handles.centersDust,1)>1 %add to existing list
a=[handles.centersDust(:,1);x] ;%to check
b=[handles.centersDust(:,2);y] ;%to check
handles.centersDust=[a b];
handles.radiiDust=[handles.radiiDust;ones(length(x),1)];
else %or to empty matrix
handles.centersDust=[x,y];
handles.radiiDust=ones(length(x),1);
end
% Update handles structure
guidata(hObject, handles);
refresh(handles);
end %obsolete here % --- Executes on button press in AddDust.
function RemoveCol_Callback(hObject, eventdata, handles) % --- Executes on button press in RemoveCol.
if sum(size(handles.l))==0; %the list doesn't exist
errordlg('please load a image series')
return
end
handles.centersBack=handles.centers; %saving for undo purpose
handles.radiiBack=handles.radii; %saving for undo purpose
% instructions to users
set(handles.UserMess, 'String', 'click on one colony to remove');
%get position
[X1, Y1] = ginput(1);
%calculate distance to click
dist=zeros(1,length(handles.centers(:,1)));
for i=1:length(handles.centers(:,1))
dist(i) = norm([handles.centers(i,1) - X1 handles.centers(i,2) - Y1]);
end
dist=dist';
in=(handles.radii>dist); %clicked inside
handles.centers=handles.centers(in==0,:); %remove from centers
handles.radii=handles.radii(in==0); %remove from radii
% Update handles structure
handles.counts{handles.i,1}=handles.centers;
handles.counts{handles.i,2}=handles.radii;
guidata(hObject, handles);
%refresh Graph
refresh(handles,1);
end
%% apperance on images
function updateRad_Callback(hObject, eventdata, handles)
% hObject handle to updateRad (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
if sum(size(handles.l))==0; %the list doesn't exist
errordlg('please load a image series')
return
end
%in the end, this is just a refresh function:
refresh(handles,1);
end % --- Executes on button press in updateRad.
function Rad_Callback(hObject, eventdata, handles)
% hObject handle to Rad (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of Rad as text
% str2double(get(hObject,'String')) returns contents of Rad as a double
appRadN = str2double(get(hObject, 'String'));
if isnan(appRadN)
set(hObject, 'String', 0);
errordlg('Input must be a number','Error');
end
% Save the new minRad value
handles.apR = appRadN;
guidata(hObject,handles)
end
function Rad_CreateFcn(hObject, eventdata, handles)
% hObject handle to Rad (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
end % --- Executes during object creation, after setting all properties.
%% automatic analyse of images
% Setting properties.
function sensitivity_CreateFcn(hObject, eventdata, handles)
% hObject handle to sensitivity (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
end %OK
function sensitivity_Callback(hObject, eventdata, handles)
% hObject handle to maxRad (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
sensitivity = str2double(get(hObject, 'String'));
if isnan(sensitivity)
set(hObject, 'String', 0);
errordlg('Input must be a number','Error');
end
% Save the new maxRad value
handles.sensitivityN = sensitivity;
guidata(hObject,handles)
end %OK
function minRad_CreateFcn(hObject, eventdata, handles) %#ok<*INUSD,*DEFNU>
% hObject handle to minRad (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: popupmenu controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
end
function minRad_Callback(hObject, eventdata, handles)
% hObject handle to minRad (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of minRad as text
% str2double(get(hObject,'String')) returns contents of minRad as a double
minRadN = str2double(get(hObject, 'String'));
if isnan(minRadN)
set(hObject, 'String', 0);
errordlg('Input must be a number','Error');
end
% Save the new minRad value
handles.minRadN = minRadN;
guidata(hObject,handles)
% --- Executes during object creation, after setting all properties.
end
function maxRad_CreateFcn(hObject, eventdata, handles)
% hObject handle to maxRad (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: popupmenu controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
end
function maxRad_Callback(hObject, eventdata, handles)
% hObject handle to maxRad (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of maxRad as text
% str2double(get(hObject,'String')) returns contents of maxRad as a double
maxRadN = str2double(get(hObject, 'String'));
if isnan(maxRadN)
set(hObject, 'String', 0);
errordlg('Input must be a number','Error');
end
% Save the new maxRad value
handles.maxRadN = maxRadN;
guidata(hObject,handles)
end
% Push buttons
function Recalc1_Callback(hObject, eventdata, handles) % --- Executes on button press in Recalc1, finds cicles in current image
% hObject handle to Recalc1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
if sum(size(handles.l))==0; %the list doesn't exist
errordlg('please load a image series')
return
end
tic
range1=[handles.minRadN handles.maxRadN];
rgb = handles.rgb;
%test=handles.sauvolarange
%find circles
set(handles.UserMess, 'String', 'calculating threshold...');guidata(hObject, handles);pause(0.05); %pause was needed to force refresh
rgbT=sauvola(rgb(:,:,2), handles.sauvolarange); %thresholding on the rgb image
set(handles.UserMess, 'String', 'searching for colonies...');guidata(hObject, handles);pause(0.05); %pause was needed to force refresh
[handles.centers,handles.radii]= imfindcircles(rgbT,range1,...
'ObjectPolarity','bright', 'Sensitivity',handles.sensitivityN, 'Method', 'Twostage');
handles.counts{handles.i,1}=handles.centers;
handles.counts{handles.i,2}=handles.radii;
guidata(hObject, handles);
set(handles.UserMess, 'String', ['recalculated for image' num2str(handles.i)]);
refresh(handles,0);
set(handles.timeRemain, 'String', ['took ',num2str(floor(toc)),' seconds for 1 frame']);
end
function AnalyseAllImages_Callback(hObject, eventdata, handles) % --- Executes on button press in AnalyseAllImages.
% hObject handle to AnalyseAllImages (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
tic
rgb = handles.rgb;
range1=[handles.minRadN handles.maxRadN];
set(handles.UserMess, 'String', 'calculating threshold...');guidata(hObject, handles);pause(0.05); %pause was needed to force refresh
rgbT=sauvola(rgb(:,:,2), handles.sauvolarange); %thresholding on the rgb image
set(handles.UserMess, 'String', 'searching for colonies...');guidata(hObject, handles);pause(0.05); %pause was needed to force refresh
[handles.centers,handles.radii]= imfindcircles(rgbT,range1,...
'ObjectPolarity','bright', 'Sensitivity',handles.sensitivityN, 'Method', 'TwoStage');
handles.counts{handles.i,1}=handles.centers;
handles.counts{handles.i,2}=handles.radii;
guidata(hObject, handles);
set(handles.UserMess, 'String', ['recalculated for image' num2str(handles.i)]);
istart=handles.i;
while handles.i<length(handles.l) %going for all the next slides
%what could have been programmed
% handles.i=handles.i+1
% test = handles.i
% %next_Callback(hObject, eventdata, handles)
% guidata(hObject, handles);
% Recalc1_Callback(hObject, eventdata, handles);
%
% set(handles.UserMess, 'String', ['recalculated for image' num2str(handles.i)]);
% %refresh(handles); %might be slowing things down here, but well...
% timeElapsed=floor(toc);
% percDone=(handles.i-istart+1)/(length(handles.l)-istart+1)*100;
% set(handles.timeRemain, 'String', {[num2str(percDone), '% done']; ['Est. ',...
% num2str((1-percDone/100)*timeElapsed/percDone*100), 's remain' ]});
%what was copy pasted
handles.i=handles.i+1;
guidata(hObject, handles);
refresh(handles,0);
range1=[handles.minRadN handles.maxRadN];
handles.rgb = imread([handles.dir, '/',handles.l(handles.i).name]); %load pic
rgb = handles.rgb;
%find circles
set(handles.UserMess, 'String', 'calculating threshold...');guidata(hObject, handles);pause(0.05); %pause was needed to force refresh
rgbT=sauvola(rgb(:,:,2), handles.sauvolarange); %thresholding on the rgb image
set(handles.UserMess, 'String', 'searching for colonies...');guidata(hObject, handles);pause(0.05); %pause was needed to force refresh
[handles.centers,handles.radii]= imfindcircles(rgbT,range1,...
'ObjectPolarity','bright', 'Sensitivity',handles.sensitivityN, 'Method', 'TwoStage');
handles.counts{handles.i,1}=handles.centers;
handles.counts{handles.i,2}=handles.radii;
guidata(hObject, handles);
set(handles.UserMess, 'String', ['recalculated for image' num2str(handles.i)]);
%refresh function has trouble updating the handle. reproducing it here
handles.rgb = imread([handles.dir, '/',handles.l(handles.i).name]); %load pic
hold off;
imshow(handles.rgb,'InitialMagnification', 25)
%showing circles (if handles.counts{handles.i,1} exists)
if handles.i<=size(handles.counts,1)
if ~isempty(handles.counts{handles.i,1})
viscircles(handles.counts{handles.i,1},handles.counts{handles.i,2}*handles.apR); %ploting with small diameter to enhance visualisation
end
set(handles.NumCells, 'String', num2str(size(handles.counts{handles.i,2},1)));
if isempty(handles.centers)
handles.centers=handles.counts{handles.i,1};
handles.radii=handles.counts{handles.i,2}; %splitting in two variables
end
else
handles.centers=[];
handles.radii=[]; %splitting in two variables
end
%updating user messages
set(handles.imageNumber, 'String', ['image number ',num2str(handles.i), ' out of ', num2str(length(handles.l))]); pause(0.05);
guidata(hObject, handles);
saveall(handles);
%message to user
timeElapsed=floor(toc);
percDone=(handles.i-istart+1)/(length(handles.l)-istart+1)*100;
remT=floor((1-percDone/100)*timeElapsed/percDone*100);
if remT<120
mess=[num2str(remT),' s'];
else
mess=[num2str(remT/60),' min'];
end
set(handles.timeRemain, 'String', {[num2str(percDone), '% done']; ['Est. ',mess, ' remain' ]});
end
end
%functions for image analysis
function output=sauvola(image, varargin)
%SAUVOLA local thresholding.
% BW = SAUVOLA(IMAGE) performs local thresholding of a two-dimensional
% array IMAGE with Sauvola algorithm.
%
% BW = SAUVOLA(IMAGE, [M N], THRESHOLD, PADDING) performs local
% thresholding with M-by-N neighbourhood (default is 3-by-3) and
% threshold THRESHOLD between 0 and 1 (default is 0.34).
% To deal with border pixels the image is padded with one of
% PADARRAY options (default is 'replicate').
%
% Example
% -------
% imshow(sauvola(imread('eight.tif'), [150 150]));
%
% See also PADARRAY, RGB2GRAY.
% For method description see:
% http://www.dfki.uni-kl.de/~shafait/papers/Shafait-efficient-binarization-SPIE08.pdf
% Contributed by Jan Motl (jan@motl.us)
% $Revision: 1.1 $ $Date: 2013/03/09 16:58:01 $
% Initialization
numvarargs = length(varargin); % only want 3 optional inputs at most
if numvarargs > 3
error('myfuns:somefun2Alt:TooManyInputs', ...
'Possible parameters are: (image, [m n], threshold, padding)');
end
optargs = {[3 3] 0.34 'replicate'}; % set defaults
optargs(1:numvarargs) = varargin; % use memorable variable names
[window, k, padding] = optargs{:};
if ndims(image) ~= 2 %#ok<*ISMAT>
error('The input image must be a two-dimensional array.');
end
% Convert to double
image = double(image);
% Mean value
mean = averagefilter(image, window, padding);
% Standard deviation
meanSquare = averagefilter(image.^2, window, padding);
deviation = (meanSquare - mean.^2).^0.5;
% Sauvola
R = max(deviation(:));
threshold = mean.*(1 + k * (deviation / R-1));
output = (image > threshold);
end % threshold function, downloaded from Matlab forum
function image=averagefilter(image, varargin)
%AVERAGEFILTER 2-D mean filtering.
% B = AVERAGEFILTER(A) performs mean filtering of two dimensional
% matrix A with integral image method. Each output pixel contains
% the mean value of the 3-by-3 neighborhood around the corresponding
% pixel in the input image.
%
% B = AVERAGEFILTER(A, [M N]) filters matrix A with M-by-N neighborhood.
% M defines vertical window size and N defines horizontal window size.
%
% B = AVERAGEFILTER(A, [M N], PADDING) filters matrix A with the
% predefinned padding. By default the matrix is padded with zeros to
% be compatible with IMFILTER. But then the borders may appear distorted.
% To deal with border distortion the PADDING parameter can be either
% set to a scalar or a string:
% 'circular' Pads with circular repetition of elements.
% 'replicate' Repeats border elements of matrix A.
% 'symmetric' Pads array with mirror reflections of itself.
%
% Comparison
% ----------
% There are different ways how to perform mean filtering in MATLAB.
% An effective way for small neighborhoods is to use IMFILTER:
%
% I = imread('eight.tif');
% meanFilter = fspecial('average', [3 3]);
% J = imfilter(I, meanFilter);
% figure, imshow(I), figure, imshow(J)
%
% However, IMFILTER slows down with the increasing size of the
% neighborhood while AVERAGEFILTER processing time remains constant.
% And once one of the neighborhood dimensions is over 21 pixels,
% AVERAGEFILTER is faster. Anyway, both IMFILTER and AVERAGEFILTER give
% the same results.
%
% Remarks
% -------
% The output matrix type is the same as of the input matrix A.
% If either dimesion of the neighborhood is even, the dimension is
% rounded down to the closest odd value.
%
% Example
% -------
% I = imread('eight.tif');
% J = averagefilter(I, [3 3]);
% figure, imshow(I), figure, imshow(J)
%
% See also IMFILTER, FSPECIAL, PADARRAY.
% Contributed by Jan Motl (jan@motl.us)
% $Revision: 1.2 $ $Date: 2013/02/13 16:58:01 $
% Parameter checking.
numvarargs = length(varargin);
if numvarargs > 2
error('myfuns:somefun2Alt:TooManyInputs', ...
'requires at most 2 optional inputs');
end
optargs = {[3 3] 0}; % set defaults for optional inputs
optargs(1:numvarargs) = varargin;
[window, padding] = optargs{:}; % use memorable variable names
m = window(1);
n = window(2);
if ~mod(m,2)
m = m-1;
end % check for even window sizes
if ~mod(n,2)
n = n-1;
end
if (ndims(image)~=2) % check for color pictures
display('The input image must be a two dimensional array.')
display('Consider using rgb2gray or similar function.')
return
end
% Initialization.
[rows,columns] = size(image); % size of the image
% Pad the image.
imageP = padarray(image, [(m+1)/2 (n+1)/2], padding, 'pre');
imagePP = padarray(imageP, [(m-1)/2 (n-1)/2], padding, 'post');
% Always use double because uint8 would be too small.
imageD = double(imagePP);
% Matrix 't' is the sum of numbers on the left and above the current cell.
t = cumsum(cumsum(imageD),2);
% Calculate the mean values from the look up table 't'.
imageI = t(1+m:rows+m, 1+n:columns+n) + t(1:rows, 1:columns)...
- t(1+m:rows+m, 1:columns) - t(1:rows, 1+n:columns+n);
% Now each pixel contains sum of the window. But we want the average value.
imageI = imageI/(m*n);
% Return matrix in the original type class.
image = cast(imageI, class(image));
end % threshold function, downloaded from Matlab forum
%% timelapse analysis
function RecalcNext_Callback(hObject, eventdata, handles) % --- Executes on button press in RecalcNext.
% the computer will calculate the growth curves assuming the pictures folder is an ordered timelapse movie.
if sum(size(handles.l))==0; %the list doesn't exist
errordlg('please load a image series')
return
end
%ask user if analysisng over all colonies and timepoints
prompt = {'How many colonies? Which colonies?','How many times? Which times'};
dlg_title = 'Parameters for timelapse analysis (0=all, if several input separate by space)'; num_lines = 1;
defaultans = {'0','0'};
answer = inputdlg(prompt,dlg_title,num_lines,defaultans);
if isempty(answer); return; end; %user cancelled
%colonies
UserColNb=str2num(answer{1,1}); %#ok<ST2NM> %user input
if sum(UserColNb==0)>=1 % contains a zero: over all colonies
colList=1:size(handles.counts{handles.i,2},1); %over all colonies
elseif size(UserColNb,2)>1 %user input more than one colony
colList=min(UserColNb,size(handles.counts{handles.i,2},1)); %at the risk of doing several time the last one...
else
colList=1:min(size(handles.counts{handles.i,2},1),UserColNb);
end
%time
UserTimeNb=str2num(answer{2,1}); %#ok<ST2NM>
nbtimes=length(handles.l);
if UserTimeNb==0
timeList=nbtimes:-1:1;
deltaT=1; %in this case, only used for user messages
elseif size(UserTimeNb,2)>1 %user input more than one timepoint <====================need to introduce sorting!
timeList=min(UserTimeNb,nbtimes);
timeList=timeList(end:-1:1);
deltaT=1; %in this case, only used for user messages
else
deltaT=round(nbtimes/UserTimeNb);
timeList=nbtimes:-deltaT:1;
end
%setting up parameters
showPlot=handles.showplot; %this is an internal parameter to be made accessible. It allows user visualisation of timelapse analysis
percsizeMean=handles.percsizeMean; % total image area to define the zero
Tresh=handles.Tresh; %Threshold under which there is no colony (in fold of min)
Numtresh=handles.Numtresh; %number of values needed to call threshold reached
tres=handles.tres; % # of grid points for theta coordinate (change to needed binning)
%create empty variables
Rad=cell(max(colList),length(timeList)); % a cell containing every colony for everytimepoint
RadMean=nan(size(Rad)); %same, but will contain mean radii. A matrix is enough
RadMean2=nan(size(Rad)); %same, but will contain mean radii. A matrix is enough
tic
set(handles.UserMess, 'String', 'starting analysis');
refresh(handles,0);