forked from mktiede/GetContours
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGetContours.m
3086 lines (2695 loc) · 94.5 KB
/
GetContours.m
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 varargout = GetContours(varargin)
%GETCONTOURS - extract contours from US movie frames
%
% usage: GetContours(fName, ...) % to initialize
%
% displays current FRAME from movie or DICOM FNAME
% click along contour to place anchor points
% click and drag on a point to reposition it
% control (right) click on a point deletes it
% shift (mid) click on a point reports anchor point info
% undo reverts to previous anchor positions
% hold shift (50 ms), control (200 ms), alt/command (500 ms) to slow image cycling
%
% use menu entries to adjust anchor points and image display
%
% supported optional 'NAME',VALUE parameter pairs:
% ANCHORS - seed initial frame with these anchor points [nAnchors x X,Y]
% AUDIO - display available audio track if true (default); click on it to set frame
% CLEAN - ignore any previous data if true (logical 1)
% CONFIG - a struct specifying display properties to modify; valid fields are
% DOTSIZE, DOTCOLOR, LINEWIDTH, LINECOLOR
% CROP - crop displayed image to cropped rectangle [Xmin Ymin width height]
% IMGMOD - procedure applied to every image before loading (e.g. @histeq)
% FRAME - initial frame to display (default is first keyframe, first if none)
% KEYFRAME - key frame list (default none)
% MPP - mm/pixel ratio (default none)
% NPOINTS - number of points / contour (default 100)
% ORIGIN - probe origin [X,Y] in ULC pixel coordinates (default none)
% RESIZE - resize displayed image by specified factor (applies after any cropping)
% TEXTGRID - Praat TextGrid and tier to parse for key frames (see examples)
% note that only labeled intervals are used but all point labels used
% TRACKER - automatic contour-fitting procedure (e.g. @gct_SLURP)
% VNAME - output variable name (defaults to FNAME)
%
% VNAME is an array-of-structs for each frame with labeled contours, with fields
% FRAME - frame number
% XY - ULC-based image coordinates describing contour [nPoints x X,Y]
% ANCHORS - associated contour spline anchor points [nAnchors x X,Y]
% NOTE - optional annotation
%
% if VNAME exists as a variable in the workspace its values are loaded and it is
% renamed to VNAME_old (VNAME is updated with values from the new session)
%
% the current position of the XY contour and ANCHORS for that FRAME are updated
% to VNAME when the current frame is changed or when closing the window
%
% when the window is closed, VNAME.mat is created within the current working directory
% containing variable VNAME with fields as above with additional
% TIME - frame offset in secs from start of movie
% IMAGE - grayscale image at current frame (if INCLUDE IMAGES parameter enabled)
%
% additional GetContours windows may be opened, but only the first permits editing
%
% contours, associated frame numbers and images may be exported to the workspace
% before closing the GetContours window using
% [contours,frames,images] = GetContours('EMIT'); % [nRows x nCols x nFrames] images
% contour = GetContours('EMIT',FRAME); % emit only specified frame(s)
% coordinates are in ULC-origin pixel units [NPOINTS x X,Y]; if origin and mm/pixel values
% available two additional columns give origin-centered mm values
%
% to extract contours from VNAME use
% contours = reshape(cell2mat({VNAME.XY}),[NPOINTS 2 length(VNAME)]);
%
% Example: get contours and associated frames from VNAME 'foo'
% GetContours('movie.avi', 'VNAME','foo');
% [contours,frames] = GetContours('EMIT'); % [nPoints x X,Y x nFrames]
% or equivalently
% contours = reshape(cell2mat({foo.XY}),[nPoints 2 length(foo)]);
% frames = cell2mat({foo.FRAMES})
% contours may also be EXPORTed (in long format) to a text file with GetContours,
% and subsequently converted to wide or EdgeTrak format using the RESHAPECONTOURS procedure
%
% Example: specify key frames from point or interval tier "frame" in "foo.TextGrid"
% GetContours('movie.avi', 'TEXTGRID',{'foo','frame'})
% if no tier name specified loads from the first tier found
% GetContours('movie.avi', 'TEXTGRID','foo')
% specify key frames directly, ignore any previous data
% GetContours('movie.avi', 'KEYFRAMES',[23:47 123 247:319], 'CLEAN',true)
%
% Example: crop image, use thick green lines
% cfg = struct('LINEWIDTH',2, 'LINECOLOR','g');
% GetContours('movie.avi', 'CROP',[100 43 670 503], 'CONFIG',cfg);
%
% Example: resize image by 75%, use SLURP tracker
% GetContours('movie.avi', 'RESIZE',.75, 'TRACKER',@gct_SLURP);
% Copyright (C) 2015-20 mark tiede <[email protected]>
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, version 3 or any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program. If not, see <http://www.gnu.org/licenses/>.
% mark tiede fecit
% mkt 12/13 v0.4
% mkt 07/14 v0.5 handle corrupt movie frames, display interval labels
% mkt 08/14 v0.6 support annotation, fix keyframe issues
% mkt 10/15 v0.7 support for r2014b+
% mkt 12/15 v0.8 UltraFest2015
% mkt 08/16 v0.9 bug fixes, better tracking support
% mkt 10/16 v1.0 release, fix inherit anchors into empty frame
% mkt 11/16 v1.1 fix explicit keyframes issues
% mkt 02/17 v1.2 fix point addition order
% mkt 06/18 v2.0 support sequence processing. tracking plugins, mpp detection
% mkt 07/18 v2.1 fix TextGrid issues
% mkt 10/18 v2.2 fix initialization overwrite bug
% mkt 11/19 v2.3 mods for internal improvements
% mkt 03/20 v2.4 bug fixes, scroller, DICOM, SLURP support
% mkt 08/20 v2.5 minor bug fixes, COEF support, add gct_snake (UltraFest IX release)
% mkt 08/20 v2.6 Fourier coef shape fitting support
% mkt 08/20 v2.7 support preseeded ANCHORS
% mkt 09/20 v2.8 fix DICOM close
% mkt 09/20 v3.0 support audio panel
% mkt 09/20 v3.1 support draw mode, multiple panels
% mkt 09/20 v3.2 support info, frame differencing, anchor deletion issue
% mkt 10/20 v3.3 bug fixes
% mkt 10/20 v3.4 test all files as DICOM first, fix cfg bug
% mkt 03/21 v3.5 add measurement tool, slowdown with modifier keys on cycle
% STATE (gcf userData) defines internal state for currently displayed frame
% VNAME (defined in base ws) defines values for each visited frame
% when switching frames VNAME is updated from STATE and vice versa
persistent PLAYERH
GCver = 'v3.5'; % current version
if nargin < 1,
eval('help GetContours');
return;
end;
% strip src,evt on callbacks
if ~ischar(varargin{1}),
varargin(1:2) = [];
if get(gca,'userdata') && ~strcmp(varargin{1},'CYCLE'), return; end; % ignore callbacks while cycling
end;
% branch by action
switch upper(varargin{1}),
%-----------------------------------------------------------------------------
% ABOUT: display version and brief help
case 'ABOUT',
state = get(gcbf,'userData');
blurb = sprintf('%s\n\n%s\n%s\n%s\n%s\n\n%s', ...
'Extract contours from US movie frames:', ...
'click along contour to place anchor points', ...
'click and drag on a point to reposition it', ...
'control-click on a point deletes it', ...
'shift-click on a point reports its position', ...
sprintf('Output variable name: %s', state.VNAME));
width = 400;
height = 300;
fPos = get(gcf, 'position');
pos = [fPos(1)+(fPos(3)-width)/2 , fPos(2)+(fPos(4)-height)/2 , width , height];
cfg = dialog('name', 'About GetContours', ...
'menubar', 'none', ...
'position', pos);
uicontrol(cfg, ...
'Position', [width/2-150,height-50,300,30], ...
'Style', 'text', ...
'fontName', 'Arial', ...
'fontSize', 24, ...
'String', sprintf('GetContours %s',GCver));
uicontrol(cfg, ...
'Position', [width/2-180,height-90,360,25], ...
'Style', 'edit', ...
'fontName', 'Arial', ...
'fontSize', 12, ...
'String', 'https://github.com/mktiede/GetContours');
uicontrol(cfg, ...
'Style', 'frame', ...
'Position', [20 20 width-39 170]);
if ismac, fs = 14; else, fs = 11; end;
uicontrol(cfg, ...
'Style', 'text', ...
'HorizontalAlignment', 'left', ...
'String', blurb, ...
'fontName', 'Arial', ...
'fontSize', fs, ...
'Position', [25 25 width-46 160]);
%-----------------------------------------------------------------------------
% ANNOTATE: add label to current frame
case 'ANNOTATE',
state = get(gcbf,'userData');
v = evalin('base',state.VNAME);
frames = cell2mat({v.FRAME});
k = (state.CURFRAME == frames);
ts = GetText(v(k).NOTE, frames(k));
set(state.LH,'string',ts);
v(k).NOTE = ts;
assignin('base',state.VNAME,v);
%-----------------------------------------------------------------------------
% AVERAGING: specify frame averaging
case 'AVERAGING',
state = get(gcbf,'userData');
[enabled,win] = GetAvg(state);
if ~isempty(enabled),
state.USEAVG = enabled;
state.AVG = win;
set(gcbf,'userData',state);
end;
set(state.IH,'cdata',GetImage(state));
%-----------------------------------------------------------------------------
% CLOSE: shutdown handler
case 'CLOSE',
state = get(gcbf,'userData');
if ishandle(state.RH), delete(state.RH); end; % close contrast adjustment (if open)
delete(gcbf); % close window
if state.LOCK, return; end;
v = evalin('base',state.VNAME); % update output variable state
frames = cell2mat({v.FRAME});
k = (state.CURFRAME == frames);
v(k).XY = state.XY;
v(k).ANCHORS = state.ANCHORS;
v(k).TRKRES = state.TRKRES;
[~,k] = sort(frames);
v = v(k); % impose sequential order
v(cellfun(@isempty,{v.XY})) = []; % delete empty frames
% add additional annotation fields
if ischar(state.MH),
info = dicominfo(state.MH); % DICOM
sr = info.CineRate;
else,
sr = state.MH.FrameRate;
end;
for vi = 1 : length(v),
v(vi).TIME = (v(vi).FRAME-1)/sr; % frame offset in secs from start of movie
if state.PARAMS.SAVEIMG,
try,
v(vi).IMAGE = GetMovieFrame(state.MH,v(vi).FRAME,state.CROP,state.RESIZE,state.IMGMODP,state.IMGMODA{:}); % grayscale image at frame
catch,
v(vi).IMAGE = zeros(get(state.MH,'Height'),get(state.MH,'Width'),'uint8');
end
else,
v(vi).IMAGE = [];
end;
end;
assignin('base',state.VNAME,v); % update in workspace
SaveVar(v, state.VNAME); % write MAT file
%-----------------------------------------------------------------------------
% COEF: map shape to Fourier coefficients (requires defined contour, origin & MPP)
case 'COEF',
state = get(gcbf,'userData');
nc = 3; % # coefficients
nAnchors = size(state.ANCHORS,1);
np = state.NPOINTS;
gLen = 5;
if nAnchors < 3,
fprintf('Coefficient estimation requires at least three anchor points\n');
return;
end;
xy = state.XY;
k = [0 ; cumsum(sqrt(sum(diff(xy).^2,2)))];
xy = interp1(k, xy, linspace(0, k(end), np)', 'pchip');
[h,w] = size(get(state.IH,'cdata'));
xy(:,1) = xy(:,1) - state.ORIGIN(1);
xy(:,2) = state.ORIGIN(2) - xy(:,2);
xy = (xy * state.MPP) / (.8 * 10); % convert to cm: distance along Liljencrants tongue with schwa is 14.4 "cm", 14.4/18 = .8
xy(:,2) = xy(:,2) - max(xy(:,2)) + 3; % default DC = 3 cm
[glx,gly] = MakeGrid(np, gLen, .1, 0);
if xy(1,1) < 0, xy = flipud(xy); end; % want first point to be anterior
xy0 = xy;
if xy(1,2) > 0, % extrapolate to last polar gridline
d = hypot(xy(1,1),xy(1,2));
xy = [[d,0] ; xy];
end;
if xy(end,2) > gly(2,end), % extrapolate to last pharyngeal gridline
xy = [xy ; [xy(end,1),gly(2,end)]];
end;
k = find(xy(:,2) < gly(2,end));
xy(k,:) = [];
d = ShapeToDist(xy, glx, gly); % distance function (lips to larynx)
[DC,C,S,mag,phi] = DistToCoef(d, nc); % fitted coefficients
fprintf('\nFourier Coefficients describing current contour (Frame %d):',state.CURFRAME);
fprintf('\n DC: %5.2f',DC);
fprintf('\n Cos:'); fprintf(' %5.2f',C);
fprintf('\n Sin:'); fprintf(' %5.2f',S);
fprintf('\n Mag:'); fprintf(' %5.2f',mag); fprintf(' (constriction degree, in cm, without DC)');
fprintf('\n Phi:'); fprintf(' %5.1f',phi*180/pi); fprintf(' (constriction location, in degrees)\n');
% adjust semi-polar gridlines
idx = find(diff(gly),1,'last'); % index of first pharyngeal gridline
th = cart2pol(glx(1,1:idx),gly(1,1:idx));
[x,y] = pol2cart(th,d(1:idx));
[glx(2,1:idx),gly(2,1:idx)] = pol2cart(th,.5);
% adjust pharyngeal gridlines
N = size(glx,2); % # grid lines
y(idx:N) = gly(1,idx:N);
x(idx:N) = d(idx:N);
xy = [x(:),y(:)];
flipped = diff(glx(:,end)) > 0;
if flipped, % faces right
xy(idx:end,1) = -xy(idx:end,1);
glx(2,idx:end) = -.5;
end;
% captions
s{1} = sprintf(' DC = %5.2f', DC);
s{2} = ['Cos =', sprintf('%6.2f',C)];
s{3} = ['Sin =', sprintf('%6.2f',S)];
s{4} = ['Mag =', sprintf('%6.2f',DC+mag)];
s{5} = ['Phi =', sprintf('%6.2f',phi*180/pi)];
[xy,d] = CoefToShape(C, S, DC, glx, gly);
figure('position',[35 571 560 420],'name',sprintf('Frame %04d', state.CURFRAME));
axes('position',[.1 .75 .82 .2])
h = plot(d,'linewidth',2);
hh = line(get(gca,'xlim'),[DC;DC],'color','k');
cs = {'DC'}; for k = 1 : length(h), cs{end+1} = sprintf('Coef %d',k); end;
legend([hh;h],cs{:});
ylabel('Magnitude (cm)'); grid on;
x = round([0:8]*N/8);
for k = 1 : length(x), xs{k} = sprintf('%d',(k-1)*45-180); end;
set(gca,'ylim',[0 gLen], 'xlim',[1 N], 'xtick',x, 'xticklabel',xs);
text(1,gLen+.1,'Lips','fontSize',11,'verticalAlignment','bottom');
text(N,gLen+.1,'Larynx','fontSize',11,'verticalAlignment','bottom','horizontalAlignment','right');
text(N/2,gLen+.1,'Phase (degrees)','fontSize',12,'verticalAlignment','bottom','horizontalAlignment','center');
axes('position',[.1 .08 .82 .6]);
line(glx,gly,'color',[.8 .8 .8]);
k = round([0:8]*N/8);
k(1) = 1;
line(glx(:,k),gly(:,k),'color','b');
box on; hold on;
h = plot(xy0(:,1),xy0(:,2),'r','linewidth',2);
k = [0 ; cumsum(sqrt(sum(diff(xy).^2,2)))];
xy = interp1(k, xy, linspace(0, k(end), state.NPOINTS)', 'pchip');
h(2) = plot(xy(:,1),xy(:,2),'color',[0 .7 0],'linewidth',2);
set(gca,'xlim',(gLen+.1)*[-1 1],'ylim',(gLen+.1)*[-1 1]);
axis equal; ylabel('cm');
legend(h,'contour','fit','location','northeast');
for k = 1 : 5, text(2,-(k/2+1),s{k},'fontname','Courier','fontsize',10,'color','k'); end
%-----------------------------------------------------------------------------
% CONFIG: configure
case 'CONFIG',
state = get(gcbf,'userData');
par = DoConfig(state.PARAMS, state.DEFPAR);
if isempty(par), return; end;
state.PARAMS = par;
state.MPP = state.PARAMS.MPP;
state.ORIGIN = state.PARAMS.ORIGIN;
set(gcbf,'userData',state);
if (~isempty(state.MPP) && ~isempty(state.ORIGIN)), es = 'on'; else, es = 'off'; end;
set(state.FCH,'enable',es);
%-----------------------------------------------------------------------------
% CYCLE: cycle through movie frames
case 'CYCLE',
if get(gca,'userdata'), % if already cycling stop
set(gca,'userdata',0);
return;
end;
state = get(gcbf,'userdata');
set(state.TMH(3),'checked','off'); % ensure tracking disabled
v = evalin('base',state.VNAME);
frames = cell2mat({v.FRAME}); % frames with data
f = state.CURFRAME;
switch varargin{2},
case 'FWD', dir = 1;
case 'BCK', dir = -1;
otherwise, set(gca,'userdata',0); return; % stop cycling
end;
% update output variable state
if dir && ~isempty(frames),
k = (state.CURFRAME == frames);
v(k).XY = state.XY;
v(k).ANCHORS = state.ANCHORS;
v(k).NOTE = get(state.LH,'string');
v(k).TRKRES = state.TRKRES;
assignin('base',state.VNAME,v);
set(state.LH,'string','');
delete(findobj(gca,'tag','CONTOUR'));
state.ALH = []; state.CLH = [];
set(gcbf,'userdata',state);
end;
% movie loop
state.IMGH.UserData = dir;
while state.IMGH.UserData,
if ~state.IMGH.UserData, break; end;
if dir > 0,
f = state.CURFRAME + 1;
if f > state.NFRAMES, f = state.NFRAMES; break; end;
else,
f = state.CURFRAME - 1;
if f < 1, f = 1; break; end;
end;
state.CURFRAME = f;
set(state.IH,'cdata',GetImage(state));
if state.ISKF(f), c = 'g'; else, c = 'y'; end;
set(state.TH,'color',c,'string',sprintf('%s',FmtFrame(f,state.FRATE)));
n = sprintf('%s [%d of %d]',state.FNAME,f,state.NFRAMES);
if ~state.LOCK, n = [n , ' (editable)']; end;
set(gcbf,'name',n, 'userdata',state);
set(state.FRAMEH, 'string', num2str(f));
set(state.SCROLLERH, 'value', f);
% update audio cursor
if ~isempty(state.AUDIO),
ff = floor(((f-1)/state.FRATE)*state.AUDIO.SRATE) + 1;
set(state.AUDIO.ACH,'xdata',[ff;ff]);
end;
drawnow;
% delay if any modifier key down
mod = get(gcbf, 'currentmodifier');
if isempty(mod), mod = ''; else, mod = mod{1}; end;
switch mod,
case {'command','alt'}, pause(.5);
case 'control', pause(.2);
case 'shift', pause(.05);
otherwise,
end;
end;
% clean up
state.IMGH.UserData = 0;
axes(state.IMGH);
% get current annotation if any
ts = '';
k = find(f == frames);
if ~isempty(k), ts = v(k).NOTE; end
% use Praat labels if no annotation
if isempty(ts) && ~isempty(state.KEYFRAMES),
if size(state.KEYFRAMES,2) == 1,
k = find(f == state.KEYFRAMES);
if ~isempty(k), ts = state.LABELS{k}; end
else,
k = find(f>=state.KEYFRAMES(:,1) & f<=state.KEYFRAMES(:,2));
if ~isempty(k), k = k(end); ts = state.LABELS{k(1)}; end
end
end
% update
k = find(f == frames);
if isempty(k), % virgin frame
if strcmpi('off',get(state.NH,'checked')),
state.ANCHORS = []; % don't inherit
state.XY = [];
end;
vv = struct('XY',state.XY,'ANCHORS',state.ANCHORS,'FRAME',f,'NOTE',ts,'TRKRES',[]);
v(end+1) = vv;
else, % update from existing anchors
if isempty(v(k).ANCHORS) && strcmpi('on',get(state.NH,'checked')),
v(k).XY = state.XY; % inherit into empty frame
v(k).ANCHORS = state.ANCHORS;
state.PREVAP = [];
else,
state.PREVAP = state.ANCHORS;
end;
state.ANCHORS = v(k).ANCHORS;
state.XY = v(k).XY;
v(k).NOTE = ts;
state.TRKRES = v(k).TRKRES;
end;
assignin('base',state.VNAME,v);
for k = 1 : size(state.ANCHORS,1),
state.ALH(k) = MakePoint(state.ANCHORS(k,1),state.ANCHORS(k,2),state.CONFIG);
end;
if ~isempty(state.XY),
state.CLH = line(state.XY(:,1),state.XY(:,2),'color',state.CONFIG.LINECOLOR,'linewidth',state.CONFIG.LINEWIDTH,'tag','CONTOUR','hitTest','off');
uistack(state.CLH,'bottom'); uistack(state.CLH,'up');
end;
% update contour line using active Tracker handler
if ~isempty(state.TRACKER),
ns = state.TRACKER('PLOT', state);
if ~isempty(ns), state = ns; end;
end;
set(gcbf,'userData',state);
%-----------------------------------------------------------------------------
% DELETE: delete existing anchors
case 'DELETE',
state = get(gcbf,'userData');
state.PREVAP = state.ANCHORS;
if strcmp(questdlg('Clear all anchors...', 'Verify...', 'Yes', 'No', 'Yes'), 'Yes'),
delete(findobj(gca,'tag','CONTOUR'));
state.CLH = []; state.ALH = []; state.ANCHORS = []; state.XY = [];
set(gcbf,'userData',UpdateContour(state));
end;
%-----------------------------------------------------------------------------
% DIFF: toggle frame differencing
case 'DIFF',
if strcmp('on',get(gcbo,'checked')),
set(gcbo,'checked','off');
else,
set(gcbo,'checked','on');
end;
state = get(gcbf,'userData');
set(state.IH,'cdata',GetImage(state));
%-----------------------------------------------------------------------------
% DOWN: mouseDown handler
%
% click in image creates new anchor point
% click on an anchor repositions it
% control-click on a point deletes it
% click and drag with no previous anchor points creates XY to which anchors are fitted
case 'DOWN',
state = get(gcbf,'userData');
state.PREVAP = state.ANCHORS;
gotPoint = (length(varargin) > 1); % nonzero for click on existing point
mod = get(gcbf,'selectionType');
cp = get(gca, 'currentPoint');
cp = cp(1,1:2);
switch mod,
case 'normal', % unmodified
% move existing point
if gotPoint,
set(gcbf, 'windowButtonMotionFcn',{@GetContours,'MOVE',gcbo}, ...
'windowButtonUpFcn',{@GetContours,'UP',gcbo}, ...
'pointer','crosshair', ...
'userData',UpdateContour(state));
% draw mode: no existing anchors
elseif length(state.ANCHORS) == 0,
lh = line(cp(1),cp(2),'color','c','linewidth',2,'tag','TEMPLINE');
set(gcbf, 'windowButtonMotionFcn',{@GetContours,'DRAW','MOVE',lh}, ...
'windowButtonUpFcn',{@GetContours,'DRAW','UP',lh}, ...
'pointer','crosshair', ...
'userData',state);
% add new point
else,
if isempty(state.TRACKER),
trackerAddPt = 0; % default processing
else, % defer to tracker
trackerAddPt = state.TRACKER('ADDPT',state,cp);
end;
if trackerAddPt < 0, return; end; % -1 flags ignore new point
lh = MakePoint(cp(1),cp(2),state.CONFIG);
% if new point is within existing points (less than half distance between nearest two points)
% then add it between those points, else append it to nearest end
n = length(state.ALH);
% if tracker returns 1 then anchor is appended to end
if trackerAddPt>0 && n>1, n = 1; end; % force append to end
switch n,
case 0, % first point
state.ALH = lh;
state.ANCHORS = cp;
case 1, % second point
state.ALH = [state.ALH , lh];
state.ANCHORS = [state.ANCHORS ; cp];
otherwise,
d = sqrt(sum((ones(size(state.ANCHORS,1),1)*cp - state.ANCHORS).^2,2));
[~,k] = min(d); % index of closest point
if k == 1, % prefix to first point
state.ALH = [lh , state.ALH];
state.ANCHORS = [cp ; state.ANCHORS];
elseif k == length(d), % append to last point
state.ALH = [state.ALH, lh];
state.ANCHORS = [state.ANCHORS ; cp];
else, % insert betweeen existing points
if d(k-1) < d(k+1), k2 = k; k = k-1; else, k2 = k+1; end;
state.ALH = [state.ALH(1:k) , lh , state.ALH(k2:end)];
state.ANCHORS = [state.ANCHORS(1:k,:) ; cp ; state.ANCHORS(k2:end,:)];
end;
end;
set(gcbf, 'userData',UpdateContour(state));
end;
% ignore double-click
case 'open',
;
% delete existing point (ctl) or echo position (shift)
otherwise,
if gotPoint,
k = find(gcbo == state.ALH); % clicked point index
if strcmp(mod,'extend'), % shift (mid)
fprintf('%d anchor points, current point located [ %d , %d ]\n', ...
length(state.ALH), round(get(state.ALH(k),'Xdata')), round(get(state.ALH(k),'Ydata')));
else, % ctl (right)
state.ANCHORS(k,:) = [];
state.ALH(k) = [];
delete(gcbo);
if isempty(state.ANCHORS), delete(state.CLH); state.CLH = []; end;
set(gcf,'userData',UpdateContour(state));
end;
end;
end;
%-----------------------------------------------------------------------------
% DRAW: draw contour
%
% varargin{2}: MOVE or UP
% varargin{3}; line handle
%
% contour drawn if no existing anchor points; on mouseUp anchors are distributed along drawn contour
case 'DRAW',
cp = get(gca, 'currentPoint');
cp = cp(1,1:2);
lh = varargin{3};
xy = [lh.XData ; lh.YData]';
if xy(end,1)~=cp(1) || xy(end,2)~=cp(2),
xy(end+1,:) = cp;
set(lh,'xdata',xy(:,1),'ydata',xy(:,2));
end;
% MOVE
if strcmp(varargin{2},'MOVE'),
drawnow;
return;
end;
% UP
set(gcbf, 'windowButtonMotionFcn','', 'windowButtonUpFcn','', 'pointer','arrow');
delete(findobj(gca,'tag','TEMPLINE'));
state = get(gcbf,'userData');
if size(xy,1) < 2, % add anchor point
state.ANCHORS = cp;
set(gcbf,'userData',UpdateContour(state));
return;
end;
% resample drawn contour
k = [0 ; cumsum(sqrt(sum(diff(xy).^2,2)))];
state.XY = interp1(k, xy, linspace(0, k(end), state.NPOINTS)', 'pchip');
% find signed curvature using central differencing
dx = gradient(state.XY(:,1)); dy = gradient(state.XY(:,2));
ddx = gradient(dx); ddy = gradient(dy);
k = (dx .* ddy - dy .* ddx) ./ (dx.^2 + dy.^2).^1.5;
% trim curvature to values whose associated radius is less than TRIM * path integral from first to last point
fk = k;
trim = .1;
if trim > 0,
q = sum(sqrt(sum(diff(xy).^2,2))) * trim;
fk(abs(1./k) > q) = 0;
end;
% count inflections (nonzero sign changes)
sfk = sign(fk);
xfk = sfk(sfk ~= 0);
if isempty(xfk),
xfk = sign(k); xfk = xfk(xfk~=0);
if isempty(xfk),
nInfl = 0; % collinear points
else,
nInfl = 1; % curvature below threshold
end;
else,
nInfl = sum(diff(xfk)~=0) + 1;
end;
if nInfl > 9, nInfl = 9; end;
nAnchors = nInfl + 2;
k = [0 ; cumsum(sqrt(sum(diff(state.XY).^2,2)))];
state.ANCHORS = interp1(k,state.XY,linspace(0,k(end),nAnchors),'linear');
set(gcbf,'userData',UpdateContour(state));
%-----------------------------------------------------------------------------
% EMIT: export contours to workspace
%
% coordinates include mm values relative to origin if mm/pixel factor and origin available
case 'EMIT',
fh = findobj('tag','GETCONTOURS');
state = get(fh,'userData');
v = evalin('base',state.VNAME); % update output variable state
frames = cell2mat({v.FRAME});
k = (state.CURFRAME == frames);
v(k).XY = state.XY;
v(k).ANCHORS = state.ANCHORS;
[n,k] = sort(frames);
v = v(k);
v(cellfun(@isempty,{v.XY})) = []; % delete empty frames
contours = reshape(cell2mat({v.XY}),[state.NPOINTS 2 length(v)]);
frames = cell2mat({v.FRAME});
if length(varargin) > 1,
idx = varargin{2};
[v,k] = intersect(frames,idx);
contours = contours(:,:,k);
frames = frames(k);
end;
if (~isempty(state.MPP) && ~isempty(state.ORIGIN)), % emit mm coordinates
mmc(:,1,:) = contours(:,1,:) - state.ORIGIN(1);
mmc(:,2,:) = state.ORIGIN(2) - contours(:,2,:); % flip
mmc = mmc * state.MPP;
varargout{1} = [contours , mmc];
else, % emit pixel coordinates
varargout{1} = contours;
end;
if nargout > 1,
varargout{2} = frames;
if nargout > 2, % include images
q = get(state.IH,'cdata');
q = zeros(size(q,1),size(q,2),length(frames),'uint8');
for f = 1 : length(frames),
q(:,:,f) = GetMovieFrame(state.MH,frames(f),state.CROP,state.RESIZE,state.IMGMODP,state.IMGMODA{:});
end;
varargout{3} = q;
end;
end;
return;
%-----------------------------------------------------------------------------
% EXPORT: save contours to tab delimited output file
%
% coordinates include mm values relative to origin if mm/pixel factor and origin available
case 'EXPORT',
fh = gcbf;
if isempty(fh), fh = findobj('tag','GETCONTOURS'); end;
state = get(fh,'userData');
[fName,pName] = uiputfile('*.tsv','Export Contours to tab-delimited text file',state.PARAMS.FNAME);
if fName == 0, return; end; % cancel
v = evalin('base',state.VNAME);
frames = cell2mat({v.FRAME}); % frames with data
k = (state.CURFRAME == frames);
if isempty(k), fprintf('no data for export\n'); return; end;
gotOrigin = (~isempty(state.MPP) && ~isempty(state.ORIGIN));
v(k).XY = state.XY;
v(k).ANCHORS = state.ANCHORS;
v(k).NOTE = get(state.LH,'string');
[n,k] = sort(frames);
v = v(k);
v(cellfun(@isempty,{v.XY})) = []; % delete empty frames
contours = reshape(cell2mat({v.XY}),[state.NPOINTS 2 length(v)]);
frames = cell2mat({v.FRAME});
notes = {v.NOTE};
sr = state.MH.FrameRate;
if gotOrigin,
mmc(:,1,:) = contours(:,1,:) - state.ORIGIN(1);
mmc(:,2,:) = state.ORIGIN(2) - contours(:,2,:); % flip
mmc = mmc * state.MPP;
end;
fid = fopen(fName,'wt');
if fid < 0, fprintf('Error attempting to open %s\n',fName); return; end;
fprintf(fid,'FRAME\tTIME\tNOTE\tPOINT\tX\tY');
if gotOrigin, fprintf(fid,'\tmmX\tmmY'); end;
fprintf(fid,'\n');
for fi = 1 : length(frames),
for ci = 1 : size(contours,1),
fprintf(fid,'%d\t%f\t%s\t%d\t%.2f\t%.2f', frames(fi), (frames(fi)-1)/sr, notes{fi}, ci, contours(ci,1,fi), contours(ci,2,fi));
if gotOrigin, fprintf(fid,'\t%.2f\t%.2f',mmc(ci,1,fi), mmc(ci,2,fi)); end;
fprintf(fid,'\n');
end;
end;
fclose(fid);
fprintf('wrote %s\n',fName);
%-----------------------------------------------------------------------------
% FILTER: show image forces
case 'FILTER',
state = get(gcbf,'userData');
img = ComputeImageForces(im2double(get(state.IH,'cdata')),state.PARAMS.SIGMA);
img = im2uint8((img-min(img(:)))./range(img(:)));
set(state.IH,'cdata',img);
%-----------------------------------------------------------------------------
% FLIP: invert image
case 'FLIP',
if strcmp(varargin{2},'HORIZONTAL'),
if strcmp(get(gca,'xdir'),'normal'),
set(gca,'xdir','reverse');
set(get(gcbo,'userdata'),'HorizontalAlignment','right');
else,
set(gca,'xdir','normal');
set(get(gcbo,'userdata'),'HorizontalAlignment','left');
end;
else,
if strcmp(get(gca,'ydir'),'normal'),
set(gca,'ydir','reverse');
else,
set(gca,'ydir','normal');
end;
end;
%-----------------------------------------------------------------------------
% FRAME: set image frame
case 'FRAME',
fh = gcbf;
if isempty(fh), fh = findobj('tag','GETCONTOURS'); end;
state = get(fh,'userData');
f = state.CURFRAME; % current frame before change
external = 0;
switch varargin{2},
case 'EXPLICIT',
external = 1;
f = varargin{3}; % called externally
case 'PREV', if f > 1, f = f - 1; end;
case 'NEXT', if f < state.NFRAMES, f = f + 1; end;
case 'SPECIFY',
f = str2num(get(state.FRAMEH,'string'));
if isempty(f),
f = state.CURFRAME;
elseif f < 1,
f = 1;
elseif f > state.NFRAMES,
f = state.NFRAMES;
end;
case 'SCROLL',
set(state.TMH(3),'checked','off'); % ensure tracking disabled
f = round(get(state.SCROLLERH,'value'));
if f < 1, f = 1; elseif f > state.NFRAMES, f = state.NFRAMES; end;
case {'KPREV','KNEXT'},
[~,k] = min(abs(state.KEYFRAMES(:,1)-f));
if strcmp(varargin{2},'KPREV'),
if k > 1, k = k - 1; end;
else,
if k < size(state.KEYFRAMES,1), k = k + 1; end;
end;
f = state.KEYFRAMES(k,1);
case {'DPREV','DNEXT'},
v = evalin('base',state.VNAME);
fr = sort(cell2mat({v.FRAME})); % frames with data
if strcmp(varargin{2},'DPREV'),
fr = fliplr(fr(fr<f));
else
fr = fr(fr>f);
end
if isempty(fr), return; end
f = fr(1);
end;
if state.CURFRAME == f, return; end; % nothing to do
state = NewFrame(state, f, 0, external);
set(fh,'userData',state);
%-----------------------------------------------------------------------------
% GETMOVIEFRAME: hook to internal GetMovieFrame; returns movie frame(s) based
% on current state parameters
%
% varargin{2}: frame(s) to return (uint8)
case 'GETMOVIEFRAME',
fh = findobj('tag','GETCONTOURS');
state = get(fh,'userData');
varargout{1} = GetMovieFrame(state.MH, varargin{2}, state.CROP, state.RESIZE, state.IMGMODP, state.IMGMODA{:});
%-----------------------------------------------------------------------------
% INFO: report current frame information
case 'INFO',
state = get(gcbf,'userData');
fprintf('Frame %s %s\n', FmtFrame(state.CURFRAME, state.FRATE), get(state.LH,'string'));
if size(state.XY,1)<state.NPOINTS || size(state.ANCHORS,1)<3, return; end;
xy = state.XY;
[~,k] = min(xy(:,2));
highPt = xy(k,:); % contour vertical max
xy2 = [xy(end,:) ; xy(1:end-1,:)];
areas = xy2(:,1).*xy(:,2) - xy(:,1).*xy2(:,2);
sa = sum(areas);
cenPt = sum((xy+xy2).*repmat(areas,1,2))./(3*sa); % centroid
cumDist = [0;cumsum(sqrt(sum(diff(xy).^2,2)))];
len = cumDist(end); % contour length
if ~isempty(state.MPP) && ~isempty(state.ORIGIN),
mmPts = [highPt ; cenPt];
mmPts(:,1) = mmPts(:,1) - state.ORIGIN(1);
mmPts(:,2) = state.ORIGIN(2) - mmPts(:,2);
mmPts = mmPts * state.MPP;
mmLen = len * state.MPP;
fprintf(' high point: [%4.0f,%4.0f] (pixels) [%5.1f,%5.1f] (mm)\n', highPt, mmPts(1,:));
fprintf(' centroid: [%4.0f,%4.0f] (pixels) [%5.1f,%5.1f] (mm)\n', cenPt, mmPts(2,:));
fprintf(' length: %.0f (pixels) %.1f (mm)\n', len, mmLen);
else,
fprintf(' high point: [%4.0f,%4.0f] (pixels)\n', highPt);
fprintf(' centroid: [%4.0f,%4.0f] (pixels)\n', cenPt);
fprintf(' length: %.0f (pixels)\n', len);
end;
try,
[~,ninfl,mci] = ComputeCurvature(xy);
fprintf(' NINFL: %d MCI: %.2f\n', ninfl, mci);
catch,
;
end;
if ~isempty(state.TRKRES) && isnumeric(state.TRKRES),
fprintf(' TRKRES: %.1f\n', state.TRKRES);
end;
%-----------------------------------------------------------------------------
% MAP: set colormap
case 'MAP',
if strcmp(get(gcbo,'text'),'Reset Original Image'),
mh = get(gcbo,'userdata');
else,
mh = gcbo;
end;
set(get(get(mh,'parent'),'children'),'checked','off');
set(mh,'checked','on');
mapName = varargin{2};
if strcmp(mapName,'Inv Gray'),
map = 1-gray;
else,
map = eval(lower(get(mh,'label')));
end;
set(gcbf,'colormap',map);
%-----------------------------------------------------------------------------
% MEASURE: measure distance
case 'MEASURE',
state = get(gcbf,'userData');
if isempty(state.MPP) || isempty(state.ORIGIN),
v = [];
else,
[v.HEIGHT,~] = size(get(state.IH,'cdata'));
v.MPP = state.MPP;
v.ORIGIN = state.ORIGIN;
end;
h = drawline('EdgeAlpha',.5,'linewidth',2,'color','y','userData',v);
addlistener(h, 'ROIClicked', @UpdateDist);
addlistener(h, 'MovingROI', @UpdateDist);
%-----------------------------------------------------------------------------
% MOVE: mouseMvt handler
case 'MOVE',
cp = get(gca, 'currentPoint');
cp = cp(1,1:2);
lh = varargin{2};
if ~ishandle(lh), return; end;
x = get(lh,'xdata');
y = get(lh,'ydata');
if x ~= cp(1) || y ~= cp(2),
set(lh, 'xdata',cp(1), 'ydata',cp(2));
state = get(gcbf,'userData');
k = find(lh == state.ALH);
state.TRKRES = []; % invalidate tracker result
state.ANCHORS(k,:) = [x,y];