-
Notifications
You must be signed in to change notification settings - Fork 0
/
videoMaker.m
1638 lines (1437 loc) · 76.3 KB
/
videoMaker.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
classdef videoMaker < matlab.mixin.Copyable
% videoMaker V1.7
% videoMaker V1.62
% updated videoMaker.getQualityFrames with findpeaks
% updated videoMaker.quality to output true false for getQualityFrames
% added legend to plotDistribution and plotDistributionOfFrame
% added mem and maxdisp to trackparticles directly for
% returnFromOdyssee in fullAnalysis.m
% updated videoMaker.returnFromOdyssee to conform with new fullAnalysis
% updated videoMaker.save to save file with workspace name and datestr
% Analyses objects in video and returns data or video with
% respective features and analysis.
%
% Object detection (based on videoFrame class) includes
% 'circle' - detects circular objects in video frame
% 'bright' (default) or 'dark' - object polarity compared to background
% 'fluorescence' (default) or 'brightfield' - clarifies image mode
% 'rect' - specify image region for detection
%
% Analysis options include
% 'tracking' - returns particle tracks from image
% 'streamlines' - calculates local flow velocities (includes tracking)
% 'distribution' - returns particle distribution, include regions to
% specify regions of interest
% 'regions' - specify regions of interest
% Analysis options can be specified during construction of videoMaker
% class or during makeVideo to include data in stream
properties
frames % array with analysis of each frame
videoLink % file destination to original video
analysis % = struct('tracking',[],'distribution',[],'streamlines',[]); % analysis from frame-by-frame data
analysisFor % define what the analysis should be performed on. Defaults to most recent image analysis.
imageType % image appearance ('fluorescence', 'brightfield', or 'darkfield')
end
properties (Dependent)
Objects % objects found in image analysis
end
properties (SetAccess = protected)
forType % analysis performed for object types
forAnalysis % analysis methods performed
rect % rectangle to crop the video
regions % relevant regions in image
options % additional parameters set for analysis and image processing
scale % for converting pixel units to physical units (factor in um/pixel, height in um)
end
properties (SetAccess = immutable)
date % creation date of the video file
end
properties (Constant, Hidden)
implementedTypes = {'circle','full','combined','twoframe'};
implementedImageTypes = {'fluorescence', 'brightfield'}; %, 'darkfield'};
implementedAnalysis = {'tracking'}; %,'distribution','streamlines'};
optionsFor = struct('tracking',{{'mem: ','maxdisp: '}});
end
%% Methods
methods
% Video analysis functions
function obj = videoMaker(videoLink,varargin) %WRITE
% obj = videoMaker(videoLink,varargin) creates a videoMaker
% object from tracking objects in the videoFile specified by
% videoLink. varargin can be used to define a custom sequence of
% analysis tools, including 'circle', 'tracking', and 'Show:
% <per number of frames>'. Default is varargin =
% {'rescale','circle','tracking','show: 500'}.
%
% obj = videoMaker() calls the videoMaker class with the
% standard sequence {'rescale','circle','tracking','show: 500
% '}.
%
% See also videoMaker.runAnalysis, videoMaker.trackParticles,
% and videoFrame.
%---------------------------------------------------------------
% Step 1 Set default variables
%---------------------------------------------------------------
obj.date = date;
if nargin < 1 || isempty(videoLink)
fileTypes = {'*.m4v','*.mov','*.avi','*.mp4'};
[name, path] = uigetfile({strjoin(fileTypes,';'),'All Video Files'},'','~/Desktop/');
if ~ischar(name)
return
end
obj.videoLink = [path, name];
else
obj.videoLink = videoLink;
end
if any(cellfun(@(str)strcmp(str,'odyssee'),lower(varargin)))
obj = obj.setupVideoAnalysisFor(varargin{:}, 'full', 'rect');
obj.prepareForOdyssee;
return
elseif isempty(varargin)
varargin = {'rescale','circle','tracking','show: 500'}; % standard operations
elseif ~any(ismember(obj.implementedTypes,lower(varargin)))
varargin{end+1} = 'circle';
end
%---------------------------------------------------------------
% Step 2 Set analysis variables
%---------------------------------------------------------------
obj = obj.setupVideoAnalysisFor(varargin{:});
%---------------------------------------------------------------
% Step 3 Analyse frames
%---------------------------------------------------------------
obj = obj.analyseFrames;
%---------------------------------------------------------------
% Step 4 Analyse video
%---------------------------------------------------------------
obj = obj.analyseVideo;
end
function obj = redoAnalysis(obj,varargin)
% obj = redoAnalysis(obj,varargin) repeats the analysis for obj
% or performs the analysis specified in varargin.
%
% obj = redoAnalysis(obj,'tracking') performs particle
% tracking analaysis for obj.
%
% See also videoMaker.runAnalysis, videoMaker.trackParticles.
% check reported properties for accuracy
if isempty(obj.analysis) && ~isempty(obj.forAnalysis); varargin = [varargin, obj.forAnalysis]; end
if isempty(obj.imageType); obj.imageType = obj.frames(1).type; end
if isempty(obj.rect); obj.rect = obj.frames(1).rect; end
if isempty(obj.rect); obj.rect = [0 0 inf inf]; end
if isempty(obj.analysisFor)
names = fieldnames(obj.frames(1).analysis);
obj.analysisFor = names{end};
end
% newAnalysis = [obj.ImplementedAnalysis, varargin];
%---------------------------------------------------------------
% Step 1 Set analysis variables
%---------------------------------------------------------------
obj = setupVideoAnalysisFor(obj,varargin{:});
%---------------------------------------------------------------
% Step 2 Redo analysis for type
%---------------------------------------------------------------
obj = obj.analyseFrames;
%---------------------------------------------------------------
% Step 3 Analyse video
%---------------------------------------------------------------
obj = obj.analyseVideo;
% update reported analysis properties
obj.forType = fieldnames(obj.frames(1).analysis)';
obj.imageType = obj.frames(1).type;
if ~isempty(obj.analysis); obj.forAnalysis = fieldnames(obj.analysis)'; end
end % check which analysis has been done and redo (make different from runAnalysis
function analysis = runAnalysis(obj,of)
% analysis = runAnalysis(obj,of) returns the analysis specified
% by of for the videoMaker object obj.
%
% analysis = runAnalysis(obj,'tracking') performs particle
% tracking analaysis for obj.
%
% See also videoMaker.runAnalysis, videoMaker.trackParticles.
switch of
case 'tracking'
analysis = trackParticles(obj);
otherwise
analysis = [];
return
end
end
% Storage and output functions
function makeVideo(obj,varargin) % UPDATE, quick makeVideo, and pretty makeVideo +
% HELP for makeVideo currently unavailable.
progress = waitbar(0,'checking analysis');
%---------------------------------------------------------------
% Step 1 Check for requested elements
%---------------------------------------------------------------
% plots = {};
% if ismember(varargin,'tracking') && isfield(obj.analysis,'tracking')
% plots = {@(obj,ax,Nr)videoMaker.plotTracks(obj,ax,Nr)};
% end
%---------------------------------------------------------------
% Step 2 Make video
%---------------------------------------------------------------
waitbar(0,progress,'locating video');
video = obj.openVideo;
% make video frame
fig = figure; title('video frame');
ax = axes(fig);
firstFrame = imcrop(readFrame(video),obj.rect); imshow(firstFrame);
ax.XLimMode = 'manual'; ax.XTickMode = 'manual'; ax.YLimMode = 'manual'; ax.YTickMode = 'manual';
% function [ax,fig] = makeFrame(video,obj,frameInd)
% time = video.CurrentTime;
% fig = figure;
% image(imcrop(readFrame(video),obj.rect)); ax = fig.Children;
% set(fig, 'Position', [0 0 obj.rect(3:4)*1.0526]);
% set(fig.Children, 'Position', [0.025 0.025 0.95 0.95],'Units','normalized');
% ax.XLimMode = 'manual'; ax.XTickMode = 'manual'; ax.YLimMode = 'manual'; ax.YTickMode = 'manual';
% imshow(readFrame(video));
% ax = fig.Children;
% if time ~= obj.frames(frameInd).time
% box(ax,'on'); ax.XTick = []; ax.YTick = [];
% ax.XColor = 'r'; ax.YColor = 'r'; ax.LineWidth = 2;
% end
% end
framesTotal = length(obj.frames); timeRem = nan(1,framesTotal);
frameInd = 2; % editedFrames(numel(obj.frames)) = getframe(makeFrame(video,obj,1)); editedFrames = fliplr(editedFrames); video.CurrentTime = 0;
editedFrames(numel(obj.frames)) = im2frame(firstFrame); editedFrames = fliplr(editedFrames); % video.CurrentTime = 0;
while hasFrame(video) && video.CurrentTime < video.Duration*1.05
tic % start clock
time = video.CurrentTime;
waitbar(time/video.Duration,progress,...
['writing frame ',num2str(frameInd),' of ',num2str(framesTotal),...
' (time rem: ',num2str(round((framesTotal-frameInd)*nanmean(timeRem)/60)),'min)']);
% [ax,fig] = makeFrame(video,obj,frameInd);
imshow(imcrop(readFrame(video),obj.rect)); % was image before, faster?
ax = fig.Children;
% PLOT DATA FROM CELL ARRAY OF FUNCTION HANDLES
% for add = plots
% add{1}(obj,ax,frameInd); % TAKES TOO LONG
% end
% if time ~= obj.frames(frameInd).time
% box(ax,'on'); ax.XTick = []; ax.YTick = [];
% ax.XColor = 'r'; ax.YColor = 'r'; ax.LineWidth = 2;
% end
videoMaker.plotTracks(obj,ax,frameInd);
% currentFrame = videoMaker.addTracksToFrame(obj,frameInd,imcrop(readFrame(video),obj.rect),[1 1 1]);
editedFrames(frameInd) = getframe(ax); %im2frame(currentFrame); %getframe(ax);
% cla(ax); close(fig);
frameInd = frameInd + 1;
timeRem(frameInd) = toc;
end
% close(fig)
waitbar(1,progress,'writing video file');
[path,name] = fileparts(obj.videoLink);
newVideo = VideoWriter([path,'/',name,'-analyzed'],'MPEG-4'); % CHANGE in varargin?
newVideo.FrameRate = video.FrameRate; % CHANGE in varargin?
% Clean out empty editedFrames
editedFrames(arrayfun(@(x)isempty(x.cdata),editedFrames)) = [];
% Write video file
open(newVideo)
writeVideo(newVideo,editedFrames);
close(newVideo)
delete(progress)
end % FINISH
function makeCrudeVideo(obj,varargin) % UPDATE, quick makeVideo, and pretty makeVideo +
% HELP for makeCrudeVideo currently unavailable.
progress = waitbar(0,'checking analysis');
%---------------------------------------------------------------
% Step 1 Check for requested elements
%---------------------------------------------------------------
plots = {};
if ismember(varargin,'tracking') && isfield(obj.analysis,'tracking')
plots = {@(obj,ax,Nr)videoMaker.plotTracks(obj,ax,Nr)};
end
%---------------------------------------------------------------
% Step 2 Make video
%---------------------------------------------------------------
waitbar(0,progress,'locating video');
video = obj.openVideo;
% function [ax,fig] = makeFrame(video,obj,frameInd)
%time = video.CurrentTime;
% fig = figure; set(fig, 'Visible', 'off');
% image(imcrop(readFrame(video),obj.rect)); ax = fig.Children;
% set(fig, 'Position', [0 0 obj.rect(3:4)*1.0526]);
% set(fig.Children, 'Position', [0.025 0.025 0.95 0.95],'Units','normalized');
% ax.XLimMode = 'manual'; ax.XTickMode = 'manual'; ax.YLimMode = 'manual'; ax.YTickMode = 'manual';
% imshow(readFrame(video));
% ax = fig.Children;
% if time ~= obj.frames(frameInd).time
% box(ax,'on'); ax.XTick = []; ax.YTick = [];
% ax.XColor = 'r'; ax.YColor = 'r'; ax.LineWidth = 2;
% end
% end
framesTotal = length(obj.frames); timeRem = nan(1,framesTotal);
frameInd = 1; % editedFrames(numel(obj.frames)) = getframe(makeFrame(video,obj,1)); editedFrames = fliplr(editedFrames); video.CurrentTime = 0;
editedFrames(numel(obj.frames)) = im2frame(readFrame(video)); editedFrames = fliplr(editedFrames); video.CurrentTime = 0;
while hasFrame(video) && video.CurrentTime < video.Duration*1.05
tic % start clock
time = video.CurrentTime;
waitbar(time/video.Duration,progress,...
['writing frame ',num2str(frameInd),' of ',num2str(framesTotal),...
' (time rem: ',num2str(round((framesTotal-frameInd)*nanmean(timeRem)/60)),'min)']);
% [ax,fig] = makeFrame(video,obj,frameInd);
%image(imcrop(readFrame(video),obj.rect));
% PLOT DATA FROM CELL ARRAY OF FUNCTION HANDLES
% for add = plots
% add{1}(obj,ax,frameInd); % TAKES TOO LONG
% end
% if time ~= obj.frames(frameInd).time
% box(ax,'on'); ax.XTick = []; ax.YTick = [];
% ax.XColor = 'r'; ax.YColor = 'r'; ax.LineWidth = 2;
% end
currentFrame = videoMaker.addTracksToFrame(obj,frameInd,imcrop(readFrame(video),obj.rect),[1 1 1]);
editedFrames(frameInd) = im2frame(currentFrame); %getframe(ax);
% cla(ax); %close(fig);
frameInd = frameInd + 1;
timeRem(frameInd) = toc;
end
% close(fig)
waitbar(1,progress,'writing video file');
[path,name] = fileparts(obj.videoLink);
newVideo = VideoWriter([path,'/',name,'-analyzed'],'MPEG-4'); % CHANGE in varargin?
newVideo.FrameRate = video.FrameRate; % CHANGE in varargin?
% Clean out empty editedFrames
editedFrames(arrayfun(@(x)isempty(x.cdata),editedFrames)) = [];
% Write video file
open(newVideo)
writeVideo(newVideo,editedFrames);
close(newVideo)
delete(progress)
end % FINISH
function trackObject(obj,n,m,varargin)
% trackObject(obj,n,m) returns an image sequence of the video
% analyzed by obj. The image sequence tracks one particle if n
% is an integer, or all particles in frames specified by n if n
% is an array of integers.
%
% trackObject(obj,n) tracks one particle if n is an integer,
% OR all particles in frames specified by n, if n is an array
% of integers.
%
% trackObject(obj,n,m) tracks all particles between seconds n
% and m of the video.
%
% See also videoMaker.trackParticles.
if nargin < 2
return
end
if any(strcmpi(varargin,'removeIdle'))
objects = videoMaker.removeStationary(obj.Objects);
elseif ~any(strcmpi(varargin,'showAll'))
objects = videoMaker.removeShortTracks(obj.Objects);
else
objects = obj.Objects;
end
% sort scenarios
if nargin == 3 && ~isempty(m)
if m < n; return; end
toDo = 'track from second n to m';
elseif length(n) < 2
toDo = 'track object n';
else
toDo = 'track frames in n';
end
% open video
video = obj.openVideo;
switch toDo
case 'track object n'
try object = obj.Objects(n);
catch me
error(me)
end
startTime = max([object.atTime(1)-0.4,0]); endTime = object.atTime(end)+0.4;
% select relevant frames and highlight object
video.CurrentTime = startTime;
numberOfFrames = round((endTime-startTime)*video.FrameRate);
sequence = uint8(zeros(video.Height,video.Width,3,numberOfFrames));
frame = 1;
while hasFrame(video) && video.CurrentTime <= endTime
location = find(video.CurrentTime == object.atTime);
Im = readFrame(video);
sequence(:,:,:,frame) = insertShape(Im,'circle', ...
[object.position(location,:)+obj.rect(1:2) object.size(location)/obj.scale.factor], ...
'LineWidth',2,'Color','red');
frame = frame + 1;
end
case 'track from second n to m'
% select relevant frames and highlight objects
objects = objects(arrayfun(@(object)any(n < object.atTime & object.atTime < m),objects));
colors = uint8(255*hsv(length(objects)));
% remove n larger than number of frames
if video.Duration < n
warning('Specified start time exceeds video duration.');
return
elseif video.Duration < m
warning('Specified end time exceeds video duration.');
end
numberOfFrames = sum(arrayfun(@(frame)n <= frame.time && frame.time <= m, obj.frames));
sequence = uint8(zeros(video.Height,video.Width,3,numberOfFrames));
% select relevant frames and highlight object
video.CurrentTime = n;
Nr = 1;
progress = waitbar(0,'grabbing frames');
while hasFrame(video) && video.CurrentTime <= m
waitbar(Nr/numberOfFrames,progress,...
['analyzing frame ',num2str(Nr),' of ',num2str(numberOfFrames)]);
locations = arrayfun(@(object)[object.position(video.CurrentTime > object.atTime - .5/video.FrameRate ...
& video.CurrentTime < object.atTime + .5/video.FrameRate,:) + obj.rect(1:2) ...
mean(object.size)/obj.scale.factor],objects,'uni',0);
clean = cellfun(@(x)size(x,2)==3,locations);
locations = vertcat(locations{clean});
Im = readFrame(video);
% add text
% anchors = [locations(:,1) + locations(:,3)/sqrt(2), locations(:,2) - 3*locations(:,3)/sqrt(2)];
% text = arrayfun(@(r){[num2str(round(r*obj.scale.factor,2)),'um']},locations(:,3));
% Im = insertText(Im,anchors,text,'TextColor',colors(clean,:),'BoxOpacity',0);
% add circle
sequence(:,:,:,Nr) = insertShape(Im,'circle',locations,'LineWidth',2,'Color',colors(clean,:));
Nr = Nr + 1;
end
delete(progress)
otherwise % 'track frames in n'
% select relevant frames and highlight objects
objects = objects(arrayfun(@(object)any(ismember(n,object.inFrame)),objects));
colors = uint8(255*hsv(length(objects)));
% remove n larger than number of frames
if any(n > numel(obj.frames))
warning('Some indices excede number of frames');
n(n > numel(obj.frames)) = [];
end
numberOfFrames = numel(n);
sequence = uint8(zeros(video.Height,video.Width,3,numberOfFrames));
progress = waitbar(0,'grabbing frames');
for Nr = 1:numberOfFrames
waitbar(Nr/numberOfFrames,progress,...
['analyzing frame ',num2str(Nr),' of ',num2str(numberOfFrames)]);
video.CurrentTime = obj.frames(n(Nr)).time;
locations = arrayfun(@(object)[object.position(object.inFrame == n(Nr),:) + obj.rect(1:2) ...
mean(object.size)/obj.scale.factor],objects,'uni',0);
%object.size(object.inFrame == n(Nr))/obj.scale.factor],objects,'uni',0);
clean = cellfun(@(x)numel(x)==3,locations);
Im = readFrame(video);
sequence(:,:,:,Nr) = insertShape(Im,'circle',vertcat(locations{clean}),'LineWidth',2,'Color',colors(clean,:));
end
delete(progress)
end
implay(sequence,video.FrameRate)
end
function makeCVS(obj,varargin) %WRITE
%HELP for makeCVS currently unavailable
end
function save(obj,path)
% save(obj,path) saves the videoMaker object obj as a matfile
% to the path specified in path. The name of the videoMaker
% object is the name of the video specified in obj.videoLink.
%
% save(obj) saves the videoMaker object under the path
% specified by videoLink.
%
% See also videoMaker.
if nargin < 2 || isempty(path)
[path,name] = fileparts(obj.videoLink);
else
[~,name] = fileparts(obj.videoLink);
end
if strcmp(inputname(1),'obj')
save([path,'/',name,' ',datestr(now),'.mat'],'obj')
else
save([path,'/',inputname(1),' ',datestr(now),'.mat'],'obj')
end
end
% Data access functions
function inRegion = objectsInRegion(obj,varargin)
% inRegion = objectsInRegion(obj,varargin) returns all objects
% specified as a list of integers in varargin. If no region
% from obj.regions is selected, it returns objects for all
% regions.
%
% See also videoMaker.setupRegions, videoMaker.trackParticles.
if isempty(obj.regions)
obj = obj.setupRegions;
end
if isempty(varargin)
regionIDs = 1:numel(obj.regions);
else
regionIDs = varargin{1};
end
objects = obj.Objects;
% filter objects based on location of droplets
inRegion = cell(size(regionIDs));
for n = regionIDs
if isempty(obj.rect)
regionXs = obj.regions{n}(1:end/2); regionYs = obj.regions{n}(1+end/2:end);
else
regionXs = obj.regions{n}(1:end/2) - obj.rect(1); regionYs = obj.regions{n}(1+end/2:end) - obj.rect(2);
end
inRegion{n} = objects(cellfun(@(pos)any(inpolygon(pos(:,1),pos(:,2),regionXs,regionYs)),{objects.position}));
end
end
function s = scatterDistribution(obj,ax,at,varargin)
if isempty(obj.regions)
obj = obj.setupRegions;
end
if nargin < 3 || isempty(at)
at = xlim(ax); at = at(2);
end
if ismember('volume',varargin(cellfun(@(c)isa(c,'char'),varargin)))
param = 'volume';
else
param = 'size';
end
if isempty(varargin(cellfun(@(c)isa(c,'numeric'),varargin)))
regionIDs = 1:numel(obj.regions);
else
regionIDs = varargin{1};
end
if isempty(regionIDs)
return
else
objects = obj.Objects;
end
if nargin < 2 || isempty(ax)
ax = axes(figure);
colormap(ax,flipud(bone))
end
% filter objects based on location of droplets
hold(ax,'on')
for n = regionIDs
if isempty(obj.rect)
regionXs = obj.regions{n}(1:2:end-1); regionYs = obj.regions{n}(2:2:end);
else
regionXs = obj.regions{n}(1:2:end-1) - obj.rect(1); regionYs = obj.regions{n}(2:2:end) - obj.rect(2);
end
inRegion = objects(cellfun(@(pos)any(inpolygon(pos(:,1),pos(:,2),regionXs,regionYs)),{objects.position}));
meanParam = arrayfun(@(obj)mean(obj.(param)),inRegion(arrayfun(@(obj)length(obj.(param)),inRegion)>2));
[values, edges] = histcounts(meanParam,100,'Normalization','Probability');
s = scatter(ax,at*ones(size(values)),edges(2:end),[],values,'filled');
end
hold(ax,'off')
end
function h = plotHistogram(obj,ax,varargin)
if isempty(obj.regions)
obj = obj.setupRegions;
end
if ismember('volume',varargin(cellfun(@(c)isa(c,'char'),varargin)))
param = 'volume';
else
param = 'size';
end
if isempty(varargin(cellfun(@(c)isa(c,'numeric'),varargin)))
regionIDs = 1:numel(obj.regions);
else
regionIDs = varargin{1};
end
if isempty(regionIDs)
return
else
objects = obj.Objects;
end
if nargin < 2 || isempty(ax)
ax = axes(figure);
end
% filter objects based on location of droplets
hold(ax,'on')
colorOrder = get(ax, 'ColorOrder');
for n = regionIDs
if isempty(obj.rect)
regionXs = obj.regions{n}(1:2:end-1); regionYs = obj.regions{n}(2:2:end);
else
regionXs = obj.regions{n}(1:2:end-1) - obj.rect(1); regionYs = obj.regions{n}(2:2:end) - obj.rect(2);
end
% inRegion = objects(cellfun(@(pos)any(inpolygon(pos(:,1),pos(:,2),regionXs,regionYs)),{objects.position}));
inRegion = @(object)inpolygon(object.position(:,1),object.position(:,2),regionXs,regionYs);
% if n == 1 % added for AG1B-5
% inRegion(arrayfun(@(obj)mean(obj.size),inRegion)<50) = [];
% end
meanParam = arrayfun(@(object)mean(object.(param)(inRegion(object))),objects(arrayfun(@(object)sum(inRegion(object))>0,objects)));
%meanParam = cell2mat(arrayfun(@(object)object.(param)(inRegion(object)),objects(arrayfun(@(object)sum(inRegion(object))>2,objects)),'uni',0));
%2 meanParam = cell2mat(arrayfun(@(obj)(obj.(param)),inRegion(arrayfun(@(obj)length(obj.(param)),inRegion)>=1),'uni',0));
% meanParam = arrayfun(@(obj)mean(obj.(param)),inRegion(arrayfun(@(obj)length(obj.(param)),inRegion)>=1));
[values, edges] = histcounts(meanParam,100,'Normalization','Probability','BinLimits',[1,100]);
h = plot(ax,edges(2:end),values,'-','Color',colorOrder(n,:));
end
hold(ax,'off')
end
function h = plotDistribution(obj,ax,varargin)
if isempty(obj.regions)
obj = obj.setupRegions;
end
if ismember('volume',varargin(cellfun(@(c)isa(c,'char'),varargin)))
param = 'volume';
else
param = 'size';
end
if any(strcmpi(varargin,'Vavg')) && strcmp(param,'volume')
adjusted = @(x,at)at.*x/trapz(at,at.*x);
elseif any(strcmpi(varargin,'Vavg')) && strcmp(param,'size')
Fadj = @(r)1e-3*(4/3*pi*r.^3 - 2*(pi/3*max([r-obj.scale.height/2;zeros(size(r))],[],1).^2.*(2*r+obj.scale.height/2)));
adjusted = @(x,at)x.*Fadj(at)/trapz(at,x.*Fadj(at));
else
adjusted = @(x,at)x;
end
if isempty(varargin(cellfun(@(c)isa(c,'numeric'),varargin)))
regionIDs = 1:numel(obj.regions);
else
regionIDs = [varargin{cellfun(@(c)isa(c,'numeric'),varargin)}];
end
if isempty(regionIDs)
return
else
objects = obj.Objects;
end
if ~any(strcmpi(varargin,'showIdle'))
objects = videoMaker.removeStationary(objects);
end
if nargin < 2 || isempty(ax)
ax = axes(figure);
end
figLegend = findobj(ax.Parent,'Type','Legend');
if isempty(figLegend)
figLegend = legend(ax);
end
% filter objects based on location of droplets
hold(ax,'on')
colorOrder = get(ax, 'ColorOrder');
for n = regionIDs
if isempty(obj.rect)
regionXs = obj.regions{n}(1:2:end-1); regionYs = obj.regions{n}(2:2:end);
else
regionXs = obj.regions{n}(1:2:end-1) - obj.rect(1); regionYs = obj.regions{n}(2:2:end) - obj.rect(2);
end
% inRegion = objects(cellfun(@(pos)any(inpolygon(pos(:,1),pos(:,2),regionXs,regionYs)),{objects.position}));
inRegion = @(object)inpolygon(object.position(:,1),object.position(:,2),regionXs,regionYs);
% if n == 1 % added for AG1B-5
% inRegion(arrayfun(@(obj)mean(obj.size),inRegion)<50) = [];
% end
meanParam = arrayfun(@(object)mean(object.(param)(inRegion(object))),objects(arrayfun(@(object)sum(inRegion(object))>0,objects)));
%meanParam = cell2mat(arrayfun(@(object)object.(param)(inRegion(object)),objects(arrayfun(@(object)sum(inRegion(object))>2,objects)),'uni',0));
%2 meanParam = cell2mat(arrayfun(@(obj)(obj.(param)),inRegion(arrayfun(@(obj)length(obj.(param)),inRegion)>=1),'uni',0));
% meanParam = arrayfun(@(obj)mean(obj.(param)),inRegion(arrayfun(@(obj)length(obj.(param)),inRegion)>=1));
if ~isempty(meanParam)
[values, at] = ksdensity(meanParam,sort([linspace(0,100,100),meanParam']));
h = plot(ax,at,adjusted(values,at),'-','Color',colorOrder(n,:));
else
h = plot(ax,nan,nan,'-','Color',colorOrder(n,:));
end
figLegend.String{end} = [inputname(1), ' Region ',num2str(n)];
end
hold(ax,'off')
end
function h = plotFrame(obj,frameID)
valid = frameID <= length(obj.frames);
v = obj.openVideo;
for ID = frameID(valid)
frameToShow = obj.frames(ID);
v.CurrentTime = frameToShow.time;
frameData = frameToShow.reportData(obj.analysisFor);
if isempty(frameData)
figure; imshow(readFrame(v))
else
centers = frameData(:,1:2) + repmat(obj.rect(1:2),size(frameData,1),1); radii = frameData(:,3);
figure; imshow(readFrame(v)); viscircles(centers, radii);
end
end
h = gca;
end
function h = plotDistributionOfFrame(obj,ax,n,varargin)
if nargin < 3
error('You need to specify a frame e.g. obj.plotDistributionOfFrame([],1)');
end
if isempty(obj.regions)
obj = obj.setupRegions;
end
if ismember('volume',varargin(cellfun(@(c)isa(c,'char'),varargin)))
param = 'volume';
else
param = 'size';
end
if any(strcmpi(varargin,'Vavg')) && strcmp(param,'volume')
adjusted = @(x,at)at.*x/trapz(at,at.*x);
elseif any(strcmpi(varargin,'Vavg')) && strcmp(param,'size')
Fadj = @(r)1e-3*(4/3*pi*r.^3 - 2*(pi/3*max([r-obj.scale.height/2;zeros(size(r))],[],1).^2.*(2*r+obj.scale.height/2)));
adjusted = @(x,at)x.*Fadj(at)/trapz(at,x.*Fadj(at));
else
adjusted = @(x,at)x;
end
if isempty(varargin(cellfun(@(c)isa(c,'numeric'),varargin)))
regionIDs = 1:numel(obj.regions);
else
regionIDs = [varargin{cellfun(@(c)isa(c,'numeric'),varargin)}];
end
if ~isnumeric(n)
if any(contains(varargin,{'best:'},'IgnoreCase',true))
best = str2double(cell2mat(...
regexp(varargin{contains(varargin,{'best:'},'IgnoreCase',true)},'\d*','Match')));
else; best = Inf;
end
vid = obj.openVideo;
spacing = str2double(cell2mat(regexp(n,'\d*','Match')))*vid.FrameRate;
n = getQualityFrames(obj,spacing,best);
end
if isempty(regionIDs)
return
else
frameData = arrayfun(@(n)reportData(obj.frames(n),obj.analysisFor),n,'uni',0);
frameData = cellfun(@(x,y)[x repmat(y,size(x,1),1)],frameData,num2cell(n),'uni',0);
P = vertcat(frameData{:});
objects = arrayfun(@(n)struct('size',P(n,3)*obj.scale.factor,'position',P(n,[1,2]),...
'volume', obj.Vol(P(n,3)*obj.scale.factor),...
'atTime',P(n,4),'inFrame',P(n,5),...
'velocity', obj.velAvg(P(n,1:2),P(n,4))*obj.scale.factor*obj.scale.slowedBy),1:size(P,1));
end
if nargin < 2 || isempty(ax)
ax = axes(figure);
end
figLegend = findobj(ax.Parent,'Type','Legend');
if isempty(figLegend)
figLegend = legend(ax);
end
% filter objects based on location of droplets
hold(ax,'on')
colorOrder = get(ax, 'ColorOrder');
for n = regionIDs
if isempty(obj.rect)
regionXs = obj.regions{n}(1:2:end-1); regionYs = obj.regions{n}(2:2:end);
else
regionXs = obj.regions{n}(1:2:end-1) - obj.rect(1); regionYs = obj.regions{n}(2:2:end) - obj.rect(2);
end
% inRegion = objects(cellfun(@(pos)any(inpolygon(pos(:,1),pos(:,2),regionXs,regionYs)),{objects.position}));
inRegion = @(object)inpolygon(object.position(:,1),object.position(:,2),regionXs,regionYs);
% if n == 1 % added for AG1B-5
% inRegion(arrayfun(@(obj)mean(obj.size),inRegion)<50) = [];
% end
Param = arrayfun(@(object)object.(param),objects(arrayfun(@(object)inRegion(object),objects)));
%meanParam = cell2mat(arrayfun(@(object)object.(param)(inRegion(object)),objects(arrayfun(@(object)sum(inRegion(object))>2,objects)),'uni',0));
%2 meanParam = cell2mat(arrayfun(@(obj)(obj.(param)),inRegion(arrayfun(@(obj)length(obj.(param)),inRegion)>=1),'uni',0));
% meanParam = arrayfun(@(obj)mean(obj.(param)),inRegion(arrayfun(@(obj)length(obj.(param)),inRegion)>=1));
if ~isempty(Param)
[values, at] = ksdensity(Param,sort([linspace(0,100,100),Param]));
h = plot(ax,at,adjusted(values,at),'-','Color',colorOrder(n,:));
else
h = plot(ax,nan,nan,'-','Color',colorOrder(n,:));
end
figLegend.String{end} = [inputname(1), ' Region ',num2str(n),' best ',num2str(best), ' frames (spaced ', num2str(spacing), ')'];
end
hold(ax,'off')
end
function plotRegions(obj,ax,varargin)
if isempty(obj.regions)
msgbox('There are currently no regions, use "obj.setupRegions" to add regions.');
return
end
if isempty(varargin(cellfun(@(c)isa(c,'numeric'),varargin)))
regionIDs = 1:numel(obj.regions);
else
regionIDs = varargin{1};
end
if isempty(regionIDs)
return
end
if nargin < 2 || isempty(ax)
% Get example image
v = obj.openVideo;
v.CurrentTime = v.Duration/2;
Im = readFrame(v);
ax = axes(figure);
imshow(Im);
end
% filter objects based on location of droplets
hold(ax,'on')
colorOrder = get(ax, 'ColorOrder');
for n = regionIDs
regionXs = obj.regions{n}(1:2:end-1); regionYs = obj.regions{n}(2:2:end);
plot(ax,regionXs,regionYs,'-','LineWidth',2,'Color',colorOrder(n,:));
text(ax,max(regionXs+7),mean(regionYs),num2str(n),'FontSize',16,'FontWeight','bold','Color',colorOrder(n,:));
end
hold(ax,'off')
end
% Data analysis functions
function estimatedPressure = estimatePressure(obj,type)
% add membrane type table (?) to constants
% get velocity of small particles
objects = videoMaker.removeStationary(obj.Objects);
objects = objects(arrayfun(@(ob)mean(ob.size) < obj.scale.height/2,objects));
meanVel = mean(vertcat(objects.velocity));
estimatedPressure = meanVel/1e6*2.9; %NaN; 2.9psi/(m/s) for IOF roughly estimated
end
function goodEnough = quality(obj,N)
% estimates quality based on number of particles tracked for
% more than N frames. Default N is 5.
if nargin < 2
N = 5;
end
% if ~strcmp(obj.imageType,'fluorescence')
% error('Cannot estimate quality of non-fluorescence videos')
% end
objects = obj.Objects;
%---------------------------------------------------------------
% Step 1 Estimate droplet detection performance
%---------------------------------------------------------------
% video = obj.openVideo;
progress = waitbar(0,'initializing frames');
% NrOfFrames = numel(obj.frames);
% Area = @(radii)sum(pi.*radii.^2);
% objectsWithMoreThanNFrames = videoMaker.removeShortTracks(objects,N);
% sizesInFrames = [vertcat(objectsWithMoreThanNFrames.size), vertcat(objectsWithMoreThanNFrames.inFrame)];
%
% foundArea = 0; totalArea = 0; timeRem = nan(1,100);
% for n = 1:NrOfFrames
% tic % start clock
% % video.CurrentTime = obj.frames(n).time;
% waitbar(n/NrOfFrames,progress,...
% ['analyzing droplet detection ',num2str(n),' of ',num2str(NrOfFrames),...
% ' (time rem: ',num2str(round((NrOfFrames-n)*nanmean(timeRem))),'s)']);
%
% foundArea = foundArea + Area(sizesInFrames(sizesInFrames(:,2) == n,1)/obj.scale.factor); %obj.frames(n).reportData);
% totalArea = totalArea + bwarea(imbinarize(rgb2gray(readFrame(video))));
%
% timeRem(rem(n,100)+1) = toc;
% end
%
% estimatedFoundArea = round(foundArea/totalArea*100);
%---------------------------------------------------------------
% Step 2 Estimate tracking performance
%---------------------------------------------------------------
waitbar(1,progress,'finishing quality estimate');
movingObjects = videoMaker.removeStationary(objects);
objectsWithLessThan2Frames = sum(arrayfun(@(obj)length(obj.size) < 2,objects));
movingObjectsWithMoreThanNFrames = sum(arrayfun(@(obj)length(obj.size) > N,movingObjects));
Nless2 = round(objectsWithLessThan2Frames/numel(objects)*100);
Nidle = round((numel(objects) - (numel(movingObjects) + objectsWithLessThan2Frames))/numel(objects)*100);
NmoreN = round(movingObjectsWithMoreThanNFrames/numel(movingObjects)*100);
%---------------------------------------------------------------
% Step 3 Report
%---------------------------------------------------------------
quality = NmoreN; % *estimatedFoundArea/100;
if quality > 70 && movingObjectsWithMoreThanNFrames > 1000; qualityStr = 'GOOD.';
elseif quality > 35 && movingObjectsWithMoreThanNFrames > 500; qualityStr = 'OK.';
else; qualityStr = 'POOR.';
end
if nargout < 1
disp(qualityStr)
% disp(['Found around ',num2str(estimatedFoundArea),'% of droplets.'])
disp(['Found ',num2str(numel(movingObjects)),' moving droplets, ',...
num2str(NmoreN), '% of which were tracked well, '])
disp(['The remaining ',num2str(numel(objects) - numel(movingObjects)),' droplets were considered idle (',num2str(Nidle),...
'%) or not tracked at all (',num2str(Nless2), '%).']);
elseif contains(qualityStr,'POOR','IgnoreCase',true)
goodEnough = false;
else
goodEnough = true;
end
delete(progress);
end
function estimate = trackingPerformance(obj,N)
% estimates tracking performance based on number of particles
% tracked for more than N frames. Default N is 5.
if nargin < 2
N = 5;
end
objects = videoMaker.removeStationary(obj.Objects);
objectsWithMoreThanNFrames = sum(arrayfun(@(obj)length(obj.size) > N,objects));
estimate = round(numel(objectsWithMoreThanNFrames)/numel(objects)*100);
end
% Dependent variable functions
function objects = get.Objects(obj)
if ~isfield(obj.analysis,'tracking')
objects = [];
return
end
% Reorient data for tracking
frameData = arrayfun(@(n)reportData(obj.frames(n),obj.analysisFor),1:numel(obj.frames),'uni',0);
frameData = cellfun(@(x,y)[x repmat(y,size(x,1),1)],frameData,num2cell(1:numel(frameData)),'uni',0);
particlePositions = sortrows(cell2mat(reshape(frameData,[],1)),[4 1 2]);
% particlePositions(:,1:2) = particlePositions(:,1:2) + repmat(obj.rect(1:2),size(particlePositions,1),1);
% Retrieve particle tracking data and sort
particleTracks = obj.analysis.tracking;
particleIDs = sortrows(particleTracks,[3 1 2]);
particles = splitapply(@(x){x},particlePositions,particleIDs(:,end));
% vol = @(r)1e-3*(4/3*pi*r.^3 - 2*(pi/3*max([r-obj.scale.height/2,zeros(size(r))],[],2).^2.*(2*r+obj.scale.height/2)));
% vel = @(p,t)sqrt(diff(p(:,1)).^2 + diff(p(:,2)).^2)./diff(t); velAvg = @(p,t)[movmean(vel(p,t),2); vel(p(max(end+(-1:0),1),1:2),t(max(end+(-1:0),1)))];
objects = cellfun(@(P)struct('size',P(:,3)*obj.scale.factor,'position',P(:,[1,2]),...
'volume', obj.Vol(P(:,3)*obj.scale.factor),...
'atTime',P(:,4),'inFrame',P(:,5),...
'velocity', obj.velAvg(P(:,1:2),P(:,4))*obj.scale.factor*obj.scale.slowedBy),particles);
end
end
%% Hidden methods
methods (Hidden = true)
% Video access functions
function v = openVideo(obj)
warning off MATLAB:subscripting:noSubscriptsSpecified
try v = VideoReader(obj.videoLink);
catch me
msgbox({'Error while opening video link:' me.message})
end
end
function obj = prepareForOdyssee(obj)
[~, name] = fileparts(obj.videoLink);
odysseeFolder = '/Users/Soren/Desktop'; %'/Volumes/homes/home00/sbrandt/Matlab';
if ~exist(odysseeFolder,'dir')
error('Odyssee folder not found.')
end
if exist([odysseeFolder,'/',name],'dir')
error('Video folder already exists.')
else
mkdir([odysseeFolder,'/',name]);
end