-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathFlowProcessing.m
More file actions
6933 lines (6122 loc) · 333 KB
/
Copy pathFlowProcessing.m
File metadata and controls
6933 lines (6122 loc) · 333 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
classdef FlowProcessing < matlab.apps.AppBase
% Properties that correspond to app components
properties (Access = public)
FlowProcessingUIFigure matlab.ui.Figure
TabGroup matlab.ui.container.TabGroup
LoadingandPreprocessingTab matlab.ui.container.Tab
CorrectionsPanel matlab.ui.container.Panel
DFW matlab.ui.control.Button
VelocityUnwrapping matlab.ui.control.Button
ProcessingPanel matlab.ui.container.Panel
MapsPushButton matlab.ui.control.Button
PulseWaveVelocityPushButton matlab.ui.control.Button
DVisualizationPanel matlab.ui.container.Panel
ManualsegmentationupdateButton matlab.ui.control.Button
mask10 matlab.ui.control.CheckBox
mask9 matlab.ui.control.CheckBox
mask8 matlab.ui.control.CheckBox
mask7 matlab.ui.control.CheckBox
mask6 matlab.ui.control.CheckBox
mask5 matlab.ui.control.CheckBox
mask4 matlab.ui.control.CheckBox
mask3 matlab.ui.control.CheckBox
mask2 matlab.ui.control.CheckBox
MaskLabel matlab.ui.control.Label
mask1 matlab.ui.control.CheckBox
SegTimeframeSpinner matlab.ui.control.Spinner
TimeframeSpinner_4Label matlab.ui.control.Label
flipSegLabel matlab.ui.control.Label
flipsegio matlab.ui.control.CheckBox
flipseglr matlab.ui.control.CheckBox
flipsegud matlab.ui.control.CheckBox
ResetRotation matlab.ui.control.Button
RotateUp matlab.ui.control.Button
RotateDown matlab.ui.control.Button
Rotate matlab.ui.control.Label
RotateRight matlab.ui.control.Button
RotateLeft matlab.ui.control.Button
View3D matlab.ui.control.UIAxes
CropPanel matlab.ui.container.Panel
FinishedCroppingButton matlab.ui.control.Button
AdjustthresholdSlider matlab.ui.control.Slider
AdjustthresholdSliderLabel matlab.ui.control.Label
FramesToUseLabel matlab.ui.control.Label
FramesToUse matlab.ui.control.EditField
CropButton_3 matlab.ui.control.Button
CropButton_2 matlab.ui.control.Button
CropButton matlab.ui.control.Button
CropInfoTable matlab.ui.control.Table
AxesZ matlab.ui.control.UIAxes
AxesY matlab.ui.control.UIAxes
AxesX matlab.ui.control.UIAxes
LoadDataPanel matlab.ui.container.Panel
InterpolateData matlab.ui.control.Button
ScanInfoTable matlab.ui.control.Table
SegmentationDirectoryEditField matlab.ui.control.EditField
SegmentationDirectoryEditFieldLabel matlab.ui.control.Label
LoadSegmentationButton matlab.ui.control.Button
DataDirectoryEditField matlab.ui.control.EditField
DataDirectoryEditFieldLabel matlab.ui.control.Label
LoadDataButton matlab.ui.control.Button
ViewDataButton matlab.ui.control.Button
VelocityUnwrappingTab matlab.ui.container.Tab
Unwrap_manual_3 matlab.ui.control.CheckBox
Unwrap_manual_2 matlab.ui.control.CheckBox
Unwrap_manual_1 matlab.ui.control.CheckBox
LaplaceUnwrap matlab.ui.control.Button
Unwrap_automatic matlab.ui.control.Button
SliceSpinner matlab.ui.control.Spinner
SliceSpinner_Label matlab.ui.control.Label
TimeframeSpinner_3 matlab.ui.control.Spinner
TimeframeSpinner_3Label matlab.ui.control.Label
Unwrap_3 matlab.ui.control.UIAxes
Unwrap_1 matlab.ui.control.UIAxes
Unwrap_2 matlab.ui.control.UIAxes
Maps matlab.ui.container.Tab
QuickviewPanel matlab.ui.container.Panel
AxialButton matlab.ui.control.Button
SagittalButton matlab.ui.control.Button
CoronalButton matlab.ui.control.Button
flipvz matlab.ui.control.CheckBox
flipvy matlab.ui.control.CheckBox
flipvx matlab.ui.control.CheckBox
MapType matlab.ui.control.DropDown
MapTime matlab.ui.control.DropDown
ResetRotation_2 matlab.ui.control.Button
RotateUp_2 matlab.ui.control.Button
RotateDown_2 matlab.ui.control.Button
Rotate_2 matlab.ui.control.Label
RotateRight_2 matlab.ui.control.Button
RotateLeft_2 matlab.ui.control.Button
CalculateMap matlab.ui.control.Button
VisOptions matlab.ui.control.Button
SaveAnimation matlab.ui.control.Button
SaveRotatedAnimation matlab.ui.control.Button
MapROIanalysis matlab.ui.control.Button
MapVolumetricanalysis matlab.ui.control.Button
PeaksystoleEditField matlab.ui.control.EditField
PeaksystoleEditFieldLabel matlab.ui.control.Label
VisualizationGroup matlab.ui.container.Panel
VisTypeDropDown matlab.ui.control.DropDown
isStreamsChanged matlab.ui.control.CheckBox
isPathlinesChanged matlab.ui.control.CheckBox
VisOptionsDropDown matlab.ui.control.DropDown
SliceSpinner_2 matlab.ui.control.Spinner
SliceSpinner_2Label matlab.ui.control.Label
TimeframeSpinner matlab.ui.control.Spinner
TimeframeSpinnerLabel matlab.ui.control.Label
VisualizationPlot matlab.ui.control.UIAxes
MapGroup matlab.ui.container.Panel
MapPlot matlab.ui.control.UIAxes
FlowandPulseWaveVelocityTab matlab.ui.container.Tab
PlaneWidth matlab.ui.control.EditField
PlanewidthmmLabel matlab.ui.control.Label
findBestFit_checkbox matlab.ui.control.CheckBox
R2Display matlab.ui.control.EditField
PWVDisplayTitle_2 matlab.ui.control.Label
deleteBranch4 matlab.ui.control.Button
BranchDropDown_4 matlab.ui.control.DropDown
Branch4Label matlab.ui.control.Label
FlipBranch1_4 matlab.ui.control.CheckBox
BranchDropDown_3 matlab.ui.control.DropDown
Branch3Label matlab.ui.control.Label
FlipBranch1_3 matlab.ui.control.CheckBox
deleteBranch3 matlab.ui.control.Button
AddbranchButton matlab.ui.control.Button
BranchDropDown_2 matlab.ui.control.DropDown
Branch2Label matlab.ui.control.Label
FlipBranch1_2 matlab.ui.control.CheckBox
deleteBranch2 matlab.ui.control.Button
BranchDropDown matlab.ui.control.DropDown
BranchDropDownLabel matlab.ui.control.Label
FlipBranch1 matlab.ui.control.CheckBox
SaveName matlab.ui.control.DropDown
SaveResultsCallback matlab.ui.control.Button
SavingTitle matlab.ui.control.Label
PWVDisplay matlab.ui.control.EditField
PWVDisplayTitle matlab.ui.control.Label
PWVType matlab.ui.control.DropDown
CalculatePWV matlab.ui.control.Button
PlotWaveformsButton matlab.ui.control.Button
PWVPoints matlab.ui.control.EditField
PWVPointsLabel matlab.ui.control.Label
PWVPointsTitle matlab.ui.control.Label
CheckcenterlinecalculateflowButton matlab.ui.control.Button
BranchNumberTitle matlab.ui.control.Label
SegmentationAndCenterline matlab.ui.container.Panel
ParameterDropDown matlab.ui.control.DropDown
ParameterLabel matlab.ui.control.Label
DisplayDistanceCheckbox matlab.ui.control.CheckBox
Reset3DviewButton matlab.ui.control.Button
View3D_2 matlab.ui.control.UIAxes
PWVCalcDisplay matlab.ui.control.UIAxes
WaveformsDisplay matlab.ui.control.UIAxes
ManageWorkspace matlab.ui.container.Tab
ClearAppAndRestartButton matlab.ui.control.Button
RestoreAppStateButton matlab.ui.control.Button
SaveAppStateButton matlab.ui.control.Button
end
% Properties that need to be accessible by companion apps (e.g. VisOptionsDialog)
properties (Access = public)
maskHandles; % cell(1,10) of mask checkbox handles – set in startupFcn
% Cached numeric vis parameters – written by VisOptionsDialog on every field change
% so that FlowProcessing.m never calls str2double at render time.
visParams = struct( ...
'minVel', 0, ...
'maxVel', 150, ...
'minQuiver', 0, ...
'maxQuiver', 100, ...
'minMap', 0, ...
'maxMap', 150);
end
properties (Access = private)
VisOptionsApp; % the VisOptions app with associated params
directory; % the data directory
segDirectory; % the directory for dicoms from a pre-defined manual segmentation
v; % the 5D velocity matrix (X x Y x Z x t x v)
nframes; % the reconstrucated cardiac time frames
res; % image dimensions in X, Y, and Z
fov; % the acquired field of view, in cm
pixdim; % resolution in X, Y, and Z, in mm
ori; % orientation (1-axial, 2-sagittal, 3-coronal)
timeres; % temporal resolution (per cardiac frame), in ms
MAG; % the 4D magitude matrix (X x Y x Z x t)
magWeightVel; % the calculated magnitude weighted velocity
angio; % a maximum intensity PCMRA
vMean; % the mean velocity over time
VENC; % velocity encoding, in mm/s
segment; % the segmentation, updated throughout
isSegmentationLoaded = 0; % is the manual segmentation loaded?
isTimeResolvedSeg = 0; % is a time-resolved segmentation loaded?
isInterpolated = 0; % is the data (and segmentation) interpolated?
isCropped = 0; % have we performed any cropping?
mask; % the mask
isRawDataCropped; % have we cropped the raw data yet?
aorta_seg; % the specific aorta segmentation
branchList; % list of all unique branches following centerline extraction
branchActual; % chosen branch for PWV measurements
area_val; % calculated area along branch
flowPerHeartCycle_vol; % resulting flow over the cardiac cycle in the aorta_seg voluem
flowPulsatile_vol; % pulsatile flow waveforms in the aorta_seg volume
contours; % the output contours calculated over the centerline, may be time-resolved
tangent_V; % in-plane perpendicular vector (V2) from params_timeResolved
vesselTangent = []; % true vessel tangent = plane normal, from fitCenterlineSpline
contourCoords = struct(); % x_full/y_full/z_full plane coords from params_timeResolved
h1; % handle for first unwrap imagesc
h2; % handle for second unwrap imagesc
h3; % handle for third unwrap imagesc
cbar_unwrap; % handle for unwrap colorbar
hpatch1; % initial 3D patch for 3D vis
patchMasks = cell(1,10); % segmentation 3D patch handles (replaces patchMask1..10)
rotAngles; % rotation angles used for viewing, can be changed by viewer
% --- isosurface geometry caches (dirty-flag pattern) ------------
segIsoFV = []; % cached isosurface for app.segment (main seg)
segIsoFV_dirty = true; % set true whenever app.segment changes
segIsoFV_coords = []; % cached [xx,yy,zz] meshgrid struct for main seg
visSegIsoFV = []; % cached isosurface for currSeg (vis tab)
visSegIsoFV_dirty = true;
isAnimating = false; % true during SaveRotatedAnimation – suppresses axis tight
usedBranches; % a list that is built up to determine which branches to perform flow measurements on
FullBranchDistance; % the full distance vector (in mm)
vectorPatch; % the patch used and updated for vectors
streamsOut = []; % struct holding calculated streamlines
streamPatch; % the patch used and updated for streamlines
pathlinesOut = []; % struct holding calculated pathlines (dataStore + time_steps)
pathlinePatch; % surface handles for pathline rendering (nParticles × 1)
pathlineInterp = []; % cached 4D griddedInterpolant structs (expensive – reuse)
sliceImg; % handle for background slice in 'slicewise'
vis3Dsurface; % the patch used for visualization plot
is3DChanged = 1; % to check if 3D segment has changed
vis3DSegsurface; % the segmentation patch used for visualization plot
is3DSegChanged = 1; % to check if loaded 3D segmentation has changed
cbar_vis; % handle for visualization colorbar
R2; % the r-squared value of the fit for cross-correlation or wavelet PWV measurement
time_peak; % the determined peak systolic phase
WSS_matrix; % calculated WSS matrix
F_matrix; % faces for 3D vis
V_matrix; % vertices for 3D vis
rotAngles2; % rotation angles used for viewing maps, can be changed by viewer
isWSScalculated = 0; % is WSS calculated
% Orientation axis widget handles (cell arrays, one per 3D axes)
% Each cell: {hX, hY, hZ, tX, tY, tZ} — three lines + three text labels
oriAxis_View3D = {};
oriAxis_VisPlt = {};
end
methods (Access = public)
% -----------------------------------------------------------------
% ORIENTATION LABEL HELPER
% Place anatomical direction labels at the ends of each 3D axis.
%
% Native-orientation display convention (view([0 0 -1])):
% MATLAB plot-X = array dim2 (columns) = ori.vylabel direction
% MATLAB plot-Y = array dim1 (rows) = ori.vxlabel direction
% MATLAB plot-Z = array dim3 (slices) = ori.vzlabel direction
%
% The labels are derived directly from the loader-supplied ori struct
% so they are correct for every scanner type and orientation without
% any coordinate transformation.
% -----------------------------------------------------------------
% -----------------------------------------------------------------
% ORIENTATION AXIS WIDGET
% Draws three orthogonal labelled axes in the upper-left corner of
% the given 3D axes. Returns handles so rotate() can be called on
% them in lock-step with the main data patches.
%
% Placement: the widget origin is fixed at the upper-left corner of
% the current data bounding box (in data coordinates). The arms
% are scaled to ~15% of the smallest FOV dimension.
%
% Axis → anatomical direction mapping for the native view([0 0 -1]):
% plot-X = array dim2 (cols) = ori.vylabel
% plot-Y = array dim1 (rows) = ori.vxlabel
% plot-Z = array dim3 (slices) = ori.vzlabel
% -----------------------------------------------------------------
function handles = drawOriAxis(app, ax)
% drawOriAxis Create (or recreate) the orientation axis widget.
% Each arm shows a single letter at its tip: the first letter of
% the axis label, which corresponds to the positive index direction
% (e.g. 'F-H' → arm points toward Foot, label = 'F').
delete(findobj(ax, 'Tag', 'ori_axis_widget'));
if ~isfield(app.ori, 'vxlabel')
handles = struct(); return;
end
xl = xlim(ax); yl = ylim(ax); zl = zlim(ax);
armLen = 0.1 * min([diff(xl), diff(yl), diff(zl)]);
if armLen <= 0, armLen = 10; end
% Widget origin: upper-left corner
ox = xl(1) + diff(xl)*0.05; if ox<1; ox = 1; end
oy = yl(1) - diff(yl)*0.05; if oy<1; oy = 1; end
oz = zl(1); if oz<1; oz = 1; end
% Tip letter = last character = direction of increasing array index
% Convention: 'F-H' means low-index=Foot, high-index=Head → tip='H'
tipX = app.ori.vylabel(end); % dim2 (cols, plot-X)
tipY = app.ori.vxlabel(end); % dim1 (rows, plot-Y)
tipZ = app.ori.vzlabel(end); % dim3 (slices, plot-Z)
hold(ax, 'on');
hX = line(ax, [ox, ox+armLen], [oy, oy], [oz, oz], ...
'Color',[0.9 0.2 0.2], 'LineWidth',2, 'Tag','ori_axis_widget');
tX = text(ax, ox+armLen*1.3, oy, oz, tipX, ...
'Color',[0.9 0.2 0.2], 'FontSize',11, 'FontWeight','bold', ...
'HorizontalAlignment','center','VerticalAlignment','middle', ...
'Tag','ori_axis_widget', 'PickableParts','none');
hY = line(ax, [ox, ox], [oy, oy+armLen], [oz, oz], ...
'Color',[0.2 0.75 0.2], 'LineWidth',2, 'Tag','ori_axis_widget');
tY = text(ax, ox, oy+armLen*1.3, oz, tipY, ...
'Color',[0.2 0.75 0.2], 'FontSize',11, 'FontWeight','bold', ...
'HorizontalAlignment','center','VerticalAlignment','middle', ...
'Tag','ori_axis_widget', 'PickableParts','none');
hZ = line(ax, [ox, ox], [oy, oy], [oz, oz+armLen], ...
'Color',[0.2 0.4 0.9], 'LineWidth',2, 'Tag','ori_axis_widget');
tZ = text(ax, ox, oy, oz+armLen*1.3, tipZ, ...
'Color',[0.2 0.4 0.9], 'FontSize',11, 'FontWeight','bold', ...
'HorizontalAlignment','center','VerticalAlignment','middle', ...
'Tag','ori_axis_widget', 'PickableParts','none');
hold(ax, 'off');
handles = struct('hX',hX,'hY',hY,'hZ',hZ,'tX',tX,'tY',tY,'tZ',tZ);
end
function rotateOriAxis(~, handles, axis_vec, angle_deg)
% rotateOriAxis Apply the same rotate() call to the widget that was
% applied to the data patches, so the widget stays in sync.
if isempty(handles) || ~isfield(handles,'hX'), return; end
objs = [handles.hX, handles.hY, handles.hZ, ...
handles.tX, handles.tY, handles.tZ];
valid = objs(isvalid(objs));
if ~isempty(valid)
rotate(valid, axis_vec, angle_deg);
end
end
% -----------------------------------------------------------------
% HELPER: return the active combined segmentation for a given frame.
% Replaces the 12+ duplicated currSeg construction blocks.
% -----------------------------------------------------------------
function currSeg = getCurrentSeg(app, t)
if app.isSegmentationLoaded
if app.isTimeResolvedSeg
currSeg = logical(app.aorta_seg(:,:,:,t));
else
activeIdx = app.getActiveMaskIndices();
if isempty(activeIdx)
currSeg = false(size(app.aorta_seg,1), size(app.aorta_seg,2), size(app.aorta_seg,3));
else
currSeg = any(app.aorta_seg(:,:,:,activeIdx), 4);
end
end
else
currSeg = logical(app.segment);
end
end
% -----------------------------------------------------------------
% HELPER: return indices of currently checked mask checkboxes.
% -----------------------------------------------------------------
function idx = getActiveMaskIndices(app)
if isempty(app.maskHandles)
idx = [];
return
end
idx = find(cellfun(@(h) h.Value, app.maskHandles));
end
function View3DSegmentation(app)
cla(app.View3D);
c = prism(size(app.aorta_seg,4));
if (app.isSegmentationLoaded)
if app.isTimeResolvedSeg
if app.maskHandles{1}.Value
aa = smooth3(app.aorta_seg(:,:,:,app.SegTimeframeSpinner.Value));
hold(app.View3D,'on')
app.patchMasks{1} = patch(app.View3D, isosurface(aa,.5), ...
'FaceColor',c(1,:),'EdgeColor','none','FaceAlpha',0.5);
reducepatch(app.patchMasks{1}, 0.6);
end
else
for ii = 1:size(app.aorta_seg, 4)
if app.maskHandles{ii}.Value
aa = smooth3(app.aorta_seg(:,:,:,ii));
hold(app.View3D,'on')
app.patchMasks{ii} = patch(app.View3D, isosurface(aa,.5), ...
'FaceColor',c(ii,:),'EdgeColor','none','FaceAlpha',0.5);
reducepatch(app.patchMasks{ii}, 0.6);
end
end
end
else
ss = smooth3(app.segment);
app.hpatch1 = patch(app.View3D, isosurface(ss, 0.5), ...
'FaceColor','red','EdgeColor','none','FaceAlpha',0.35);
reducepatch(app.hpatch1 ,0.6);
end
hold(app.View3D,'off');
% Make it all look good
camlight(app.View3D);
lighting(app.View3D,'gouraud');
lightangle(app.View3D,0,0);
view(app.View3D, [0 0 -1]);
% DataAspectRatio: [X Y Z] = [col=dim2, row=dim1, slice=dim3]
daspect(app.View3D, [app.pixdim(2), app.pixdim(1), app.pixdim(3)]);
axis(app.View3D,'off');
% Compute volume extents in physical mm (plot space is voxel indices
% but daspect scales them, so limits must still be in voxel units).
% Use the largest half-extent across all three axes so nothing clips.
nRow = size(app.segment,1);
nCol = size(app.segment,2);
nSli = size(app.segment,3);
cx = nCol/2; cy = nRow/2; cz = nSli/2;
% Half-extents in physical mm, then convert back to voxel units
hx = cx; % col voxels
hy = cy; % row voxels
hz = cz * (app.pixdim(3)/app.pixdim(1)); % slices scaled to col-voxel units
R = max([hx, hy, hz]) * 1.1;
xlim(app.View3D, [cx-R, cx+R]);
ylim(app.View3D, [cy-R, cy+R]);
zlim(app.View3D, [cz-R*app.pixdim(1)/app.pixdim(3), cz+R*app.pixdim(1)/app.pixdim(3)]);
app.oriAxis_View3D = app.drawOriAxis(app.View3D);
% Rotate around the volume centroid so the object stays centred
if sum(abs(app.rotAngles)) > 0
if app.isSegmentationLoaded
rotate(app.patchMasks{1}, [1 0 0], app.rotAngles(1), [cx cy cz]);
rotate(app.patchMasks{1}, [0 1 0], app.rotAngles(2), [cx cy cz]);
else
rotate(app.hpatch1, [1 0 0], app.rotAngles(1), [cx cy cz]);
rotate(app.hpatch1, [0 1 0], app.rotAngles(2), [cx cy cz]);
end
end
end
function reset3DSegmentationAndCenterline(app)
% Initialize figure
colorbar(app.View3D_2,'off')
cla(app.View3D_2);
currSeg = app.getCurrentSeg(app.SegTimeframeSpinner.Value);
currSeg = smooth3(double(currSeg));
hpatch = patch(app.View3D_2,isosurface(currSeg,0.5),'FaceAlpha',0.20);
reducepatch(hpatch,0.6);
set(hpatch,'FaceColor',[0.7 0.7 0.7],'EdgeColor', 'none','PickableParts','none');
unqBranches = unique(app.branchList(:,4));
c = lines(length(unqBranches));
for b = 1:length(unqBranches)
% extract coordinates for branch and plot
currBranch = find(app.branchList(:,4) == b);
hline(b) = line(app.View3D_2, ...
app.branchList(currBranch,2),app.branchList(currBranch,1),app.branchList(currBranch,3),...
'Color',c(b,:),'Marker','.','MarkerSize',12,'LineStyle','none');
end
% make it look good
axis(app.View3D_2, 'vis3d')
axis(app.View3D_2, 'off')
colormap(app.View3D_2,'colorcube')
camlight(app.View3D_2);
lighting(app.View3D_2,'gouraud');
view(app.View3D_2, [0 0 -1]);
daspect(app.View3D_2,[1 1 1])
% Put the number labels on the CenterlinePlot
numString_val = num2str(unqBranches);
for i = 1:length(unqBranches)
%find rows where textint = branchList(:,4) and take the mid point
temp = app.branchList(app.branchList(:,4) == i,1:3);
textLoc(i,1:3) = temp(round(size(temp,1)/2),:);
end
Ntxt = text(app.View3D_2,textLoc(unqBranches,2)+1,textLoc(unqBranches,1)+1,textLoc(unqBranches,3)+1,...
numString_val,'Color','k','FontSize',20,'FontWeight', 'bold','Margin', 1,...
'HitTest','off','PickableParts','none');
% update view angle
camorbit(app.View3D_2,app.rotAngles(2),app.rotAngles(1),[1 1 0])
if length(unqBranches) > 1
app.BranchDropDown.Items = string(unqBranches);
else
app.BranchDropDown.Items = {'1'};
end
end
function view3D_wParams(app)
currSeg = app.getCurrentSeg(app.SegTimeframeSpinner.Value);
% indices for flow plotting
x = round(app.branchActual(:,1));
y = round(app.branchActual(:,2));
z = round(app.branchActual(:,3));
index = sub2ind(size(currSeg),x,y,z);
%reset figure
cla(app.View3D_2);
colorbar(app.View3D_2,'off');
hpatch = patch(app.View3D_2, isosurface(smooth3(double(currSeg)),0.5),'FaceAlpha',0.25);
reducepatch(hpatch,0.6);
set(hpatch,'FaceColor',[0.7 0.7 0.7],'EdgeColor', 'none','PickableParts','none');
% grab parameter from drop-down, and set colorbar description
switch app.ParameterDropDown.Value
case 'total flow'
cdata = app.flowPerHeartCycle_vol(index);
axisText = 'flow (mL/cycle)';
case 'peak flow'
cdata = max(app.flowPulsatile_vol(index,:),[],2);
axisText = 'peak flow (mL/s)';
case 'mean velocity'
cdata = mean(app.flowPulsatile_vol(index,:)./app.area_val,2);
axisText = 'mean velocity (cm/s)';
case 'peak velocity'
cdata = max(app.flowPulsatile_vol(index,:)./app.area_val,[],2);
axisText = 'peak velocity (cm/s)';
end
hSurface = surface(app.View3D_2,'XData',[y(:) y(:)],'YData',[x(:) x(:)],'ZData',[z(:) z(:)],...
'CData',[cdata(:) cdata(:)],'FaceColor','none','EdgeColor','flat',...
'Marker','.','MarkerSize',12);
caxis(app.View3D_2,[min(cdata) max(cdata)]);
colormap(app.View3D_2,jet)
cbar = colorbar(app.View3D_2);
set(get(cbar,'xlabel'),'string',axisText,'fontsize',16,'Color','black');
set(cbar,'FontSize',14,'color','black','Location','west');
pos = get(cbar,'position');
pos = [0.01 0.01 pos(3) 0.33];
set(cbar,'position',pos);
% make it look good
axis(app.View3D_2, 'vis3d')
axis(app.View3D_2, 'off')
camlight(app.View3D_2);
lighting(app.View3D_2,'gouraud');
view(app.View3D_2, [0 0 -1]);
daspect(app.View3D_2,[1 1 1])
% Put the number labels on the CenterlinePlot
str = app.PWVPoints.Value;
if app.DisplayDistanceCheckbox.Value
out = textscan(str,'%f %f','Delimiter',':');
[~, minIdx] = min(abs(app.FullBranchDistance-out{1}));
[~, minIdx2] = min(abs(app.FullBranchDistance-out{2}));
textint = app.FullBranchDistance(minIdx:5:minIdx2);
textint2 = minIdx:5:minIdx2;
else
ptRange = str2num(str);
ptRange(ptRange>length(app.branchActual)) = [];
textint2 = ptRange(1:5:end); textint = textint2;
end
numString_val = num2str(textint);
numString_val = strsplit(numString_val);
c = winter(length(textint2));
fontSz = 14;round(length(textint2)/2);
for C = 1:length(textint2)
Ntxt(C) = text(app.View3D_2,app.branchActual(textint2(C),2)-2,app.branchActual(textint2(C),1),app.branchActual(textint2(C),3),numString_val{C},...
'Color','k','HorizontalAlignment','right',...
'FontSize',fontSz,'FontWeight','Bold','HitTest','off','PickableParts','none');
end
% update view angle
camorbit(app.View3D_2,app.rotAngles(2),app.rotAngles(1),[1 1 0])
drawnow;
end
function plotWaveforms(app)
% grab waveforms
x = round(app.branchActual(:,1));
y = round(app.branchActual(:,2));
z = round(app.branchActual(:,3));
index = sub2ind(size(app.aorta_seg),x,y,z);
waveforms = app.flowPulsatile_vol(index,:);
if contains(app.ParameterDropDown.Value,'flow')
plotString = 'flow (mL/s)';
else
waveforms = waveforms./app.area_val;
plotString = 'Velocity (cm/s)';
end
view3D_wParams(app);
str = app.PWVPoints.Value;
ptRange = [];
if app.DisplayDistanceCheckbox.Value
out = textscan(str,'%f %f','Delimiter',':');
[~, minIdx] = min(abs(app.FullBranchDistance-out{1}));
[~, minIdx2] = min(abs(app.FullBranchDistance-out{2}));
ptRange = minIdx:minIdx2;
else
ptRange = str2num(str);
ptRange(ptRange>length(app.branchActual)) = [];
% reset the string to correct max
outNums = sscanf(str,'%i:%i:%i');
if length(outNums)==2
app.PWVPoints.Value = sprintf('%i:%i',outNums(1),ptRange(end));
elseif length(outNums)==3
app.PWVPoints.Value = sprintf('%i:%i:%i',outNums(1),outNums(2),ptRange(end));
end
end
waveforms = waveforms(ptRange,:);
% plot
card_time = [0:app.nframes-1]*app.timeres;
c = winter(size(waveforms,1));
if size(waveforms,1) > 5
alpha = linspace(0.8,0.3,size(waveforms,1));
else
alpha = 0.8*ones(1,size(waveforms,1));
end
c = cat(2,c,alpha');
colorbar(app.WaveformsDisplay,'off')
cla(app.WaveformsDisplay);
hold(app.WaveformsDisplay,'on');
for ii = 1:size(waveforms,1)
plot(app.WaveformsDisplay,card_time,waveforms(ii,:)','Color',c(ii,:),...
'LineWidth',2)
end
xlim(app.WaveformsDisplay,[0 max(card_time)])
app.WaveformsDisplay.XLabel.String = 'Cardiac Time (ms)';
app.WaveformsDisplay.YLabel.String = plotString;
if numel(ptRange) > 1
colormap(app.WaveformsDisplay,winter);
cbar = colorbar(app.WaveformsDisplay);
set(get(cbar,'title'),'string','Point number','fontsize',16,'Color','black');
set(cbar,'FontName','Calibri','FontSize',10,'color','black');
end
% display a max of 5 points on cbar
if app.DisplayDistanceCheckbox.Value
set(get(cbar,'title'),'string','Distance (mm)','fontsize',16,'Color','black');
if size(waveforms,1) < 11
cbar.Ticks = linspace(0, 1, size(waveforms,1)) ;
cbar.TickLabels = num2cell(app.FullBranchDistance(minIdx:minIdx2));
else
cbar.Ticks = linspace(0, 1, 5) ;
cbar.TickLabels = num2cell(round(linspace(double(app.FullBranchDistance(minIdx)),...
double((app.FullBranchDistance(minIdx2))),5)));
end
else
if size(waveforms,1) < 11
cbar.Ticks = linspace(0, 1, size(waveforms,1)) ;
cbar.TickLabels = num2cell(ptRange);
else
cbar.Ticks = linspace(0, 1, 5) ;
cbar.TickLabels = num2cell(round(linspace(double(min(ptRange)),double(max(ptRange)),5)));
end
end
hold(app.WaveformsDisplay,'off');
end
function maskSz = cropImage(app,img,img2)
choice = 0;
while choice == 0
cropFig = figure(100);
set(cropFig,'Units','normalized');
set(cropFig,'Position',[0.0016 0.0481 0.4969 0.8454])
set(cropFig,'Name','Draw rectangle to crop image')
% View MIP
imagesc(img);
colormap('gray')
c = prism(size(app.aorta_seg,4));
ct = 0;
if app.isSegmentationLoaded
if app.isTimeResolvedSeg
ct = ct+1;
hold(gca,'on');
h = imagesc(cat(3,c(1,1)*ones(size(img)),c(1,2)*ones(size(img)),c(1,3)*ones(size(img))));
set(h,'AlphaData',img2(:,:,ct))
hold(gca,'off');
else
for ii = app.getActiveMaskIndices()
ct = ct+1;
hold(gca,'on');
h = imagesc(cat(3,c(ii,1)*ones(size(img)),c(ii,2)*ones(size(img)),c(ii,3)*ones(size(img))));
set(h,'AlphaData',img2(:,:,ct))
hold(gca,'off');
end
end
end
axis equal off
daspect([1 1 1]);
h = drawrectangle(gca,'DrawingArea',[1 1 size(img,2)-1 size(img,1)-1]);
maskSz = h.Position;
maskSz(1:2) = floor(maskSz(1:2));
maskSz(3:4) = ceil(maskSz(3:4));
maskSz(maskSz<1) = 1;
tmp_mask = zeros(size(img));
tmp_mask(maskSz(2):(maskSz(2)+maskSz(4)), maskSz(1):(maskSz(1)+maskSz(3))) = 1;
imgCropped = img.*tmp_mask;
clf(cropFig);
imagesc(imgCropped);
colormap('gray')
ct = 0;
if app.isSegmentationLoaded
if app.isTimeResolvedSeg
ct = ct+1;
hold(gca,'on');
h = imagesc(cat(3,c(1,1)*ones(size(img)),c(1,2)*ones(size(img)),c(1,3)*ones(size(img))));
set(h,'AlphaData',img2(:,:,ct))
hold(gca,'off');
else
for ii = app.getActiveMaskIndices()
ct = ct+1;
hold(gca,'on');
h = imagesc(cat(3,c(ii,1)*ones(size(img)),c(ii,2)*ones(size(img)),c(ii,3)*ones(size(img))));
set(h,'AlphaData',img2(:,:,ct).*tmp_mask)
hold(gca,'off');
end
end
end
axis equal off
daspect([1 1 1]);
set(cropFig,'Name','Cropped image')
choice = checkCrop;
end
% if cancel, reset the mask and img
if choice == 2
maskSz = [1 1 size(img,2)-1 size(img,1)-1];
end
% update cropped state
if choice == 1
app.isCropped = 1;
end
close(cropFig)
end
function app = cropRawData(app)
% crop in time too
str = app.FramesToUse.Value;
ptRange = str2num(str);
app.nframes = length(ptRange);
[x, y, z] = ind2sub(size(app.mask),find(app.mask));
lx = length(unique(x)); ly = length(unique(y)); lz = length(unique(z));
maskIdx = find(app.mask);
% crop velocity
tempV = reshape(app.v(:,:,:,:,ptRange),[prod(app.res),3,app.nframes]);
tempV = tempV(maskIdx,:,:);
tempV = reshape(tempV,lx,ly,lz,3,app.nframes);
app.v = tempV;
app.vMean = mean(app.v,5);
clear tempV
% crop MAG
tempMAG = reshape(app.MAG(:,:,:,ptRange),[prod(app.res),app.nframes]);
tempMAG = tempMAG(maskIdx,:);
tempMAG = reshape(tempMAG,lx,ly,lz,app.nframes);
app.MAG = tempMAG;
clear tempMAG;
% update magWeightVel and angio
[app.magWeightVel, app.angio] = calc_angio(app.MAG, app.v, app.VENC);
% others to crop, segment and aorta_seg
tempS = app.segment(:);
tempS = tempS(maskIdx);
tempS = reshape(tempS,lx,ly,lz);
app.segment = tempS;
clear tempS;
if (app.isSegmentationLoaded)
tempS = app.aorta_seg(:);
tempS = reshape(tempS,length(tempS)/size(app.aorta_seg,4),size(app.aorta_seg,4));
tempS = tempS(maskIdx,:);
tempS = reshape(tempS,lx,ly,lz,size(app.aorta_seg,4));
app.aorta_seg = tempS;
clear tempS;
else
app.aorta_seg = app.segment;
end
end
function updateMIPs(app)
% colormap for multimask
c = prism(size(app.aorta_seg,4));
% Determine which mask indices are active (computed once for all 3 axes)
if app.isSegmentationLoaded && ~app.isTimeResolvedSeg
activeMasks = app.getActiveMaskIndices();
end
tSeg = app.SegTimeframeSpinner.Value;
% Helper: overlay active mask projections onto a given axes
function overlayMasks(ax, dim, imSize, alpha)
if ~app.isSegmentationLoaded, return; end
if app.isTimeResolvedSeg
hold(ax,'on');
img2 = reshape(max(app.aorta_seg(:,:,:,tSeg),[],dim), imSize);
h = imagesc(ax, cat(3, c(1,1)*ones(imSize), c(1,2)*ones(imSize), c(1,3)*ones(imSize)));
set(h,'AlphaData', alpha*img2);
hold(ax,'off');
else
for ii = activeMasks
hold(ax,'on');
img2 = reshape(max(app.aorta_seg(:,:,:,ii),[],dim), imSize);
h = imagesc(ax, cat(3, c(ii,1)*ones(imSize), c(ii,2)*ones(imSize), c(ii,3)*ones(imSize)));
set(h,'AlphaData', 0.15*img2);
hold(ax,'off');
end
end
end
% X axis MIP
cla(app.AxesX);
imSize = size(max(app.angio,[],1)); imSize = imSize(2:3);
imagesc(app.AxesX,reshape(max(app.angio,[],1),imSize));
overlayMasks(app.AxesX, 1, imSize, 0.25);
set(app.AxesX,'XTickLabel','','YTickLabel','')
colormap(app.AxesX,'gray'); axis(app.AxesX,'equal'); daspect(app.AxesX,[1 1 1]);
set(app.AxesX,'DataAspectRatio',[app.pixdim(1) app.pixdim(3) 1])
% Y axis MIP
cla(app.AxesY);
imSize = size(max(app.angio,[],2)); imSize = imSize([1,3]);
imagesc(app.AxesY,reshape(max(app.angio,[],2),imSize));
overlayMasks(app.AxesY, 2, imSize, 0.25);
set(app.AxesY,'XTickLabel','','YTickLabel','')
colormap(app.AxesY,'gray'); axis(app.AxesY,'equal'); daspect(app.AxesY,[1 1 1]);
set(app.AxesY,'DataAspectRatio',[app.pixdim(2) app.pixdim(3) 1])
% Z axis MIP
cla(app.AxesZ);
imSize = size(max(app.angio,[],3)); imSize = imSize([1,2]);
imagesc(app.AxesZ,reshape(max(app.angio,[],3),imSize));
overlayMasks(app.AxesZ, 3, imSize, 0.25);
set(app.AxesZ,'XTickLabel','','YTickLabel','')
colormap(app.AxesZ,'gray'); axis(app.AxesZ,'equal'); daspect(app.AxesZ,[1 1 1]);
set(app.AxesZ,'DataAspectRatio',[app.pixdim(1) app.pixdim(2) 1])
end
function updateVisualization(app)
t = app.TimeframeSpinner.Value;
if t == 0, t = 1; end
% get segmentation via helper (eliminates duplicated block)
currSeg = app.getCurrentSeg(t);
% grab vis parameters – use cached numeric values where possible
if ~isvalid(app.VisOptionsApp)
scale = [0 round(app.VENC/10)];
backgroundC = [1 1 1];
axisText = [0 0 0];
cmap = 'jet';
cbarLoc = 'bottom-left';
else
if isempty(app.visParams.maxVel)
app.visParams.maxVel = app.VENC/10;
end
scale = [app.visParams.minVel, app.visParams.maxVel];
backgroundC = [1 1 1];
if strcmp(app.VisOptionsApp.backgroundDropDown.Value,'black')
backgroundC = [0 0 0];
end
axisText = [0 0 0];
if strcmp(app.VisOptionsApp.TextcolorDropDown.Value,'white')
axisText = [1 1 1];
end
cmap = app.VisOptionsApp.ColormapDropDown.Value;
cbarLoc = app.VisOptionsApp.LocationDropDown.Value;
end
clim(app.VisualizationPlot, scale);
colormap(app.VisualizationPlot, cmap);
app.VisualizationGroup.BackgroundColor = backgroundC;
app.VisualizationGroup.ForegroundColor = axisText;
app.TimeframeSpinnerLabel.FontColor = axisText;
app.SliceSpinner_2Label.FontColor = axisText;
set(get(app.cbar_vis,'xlabel'),'string','velocity (cm/s)','Color',axisText);
set(app.cbar_vis,'FontSize',13,'color',axisText,'Location','west');
pos = get(app.cbar_vis,'position');
switch cbarLoc
case 'bottom-left'
pos = [0.01 0.02 pos(3) 0.2];
case 'mid-left'
pos = [0.01 0.41 pos(3) 0.2];
case 'upper-left'
pos = [0.01 0.75 pos(3) 0.2];
case 'bottom-right'
pos = [0.99-pos(3) 0.02 pos(3) 0.2];
case 'mid-right'
pos = [0.99-pos(3) 0.41 pos(3) 0.2];
case 'upper-right'
pos = [0.99-pos(3) 0.75 pos(3) 0.2];
end
set(app.cbar_vis,'position',pos);
delete(findall(app.VisualizationPlot,'Type','light'))
% toggle 3D surfaces
% vis3Dsurface = background anatomy shell (app.segment, full FOV)
% vis3DSegsurface = vessel of interest (currSeg / aorta_seg)
% Both use pixdim-scaled grids so they share the same mm coordinate space.
if app.VisOptionsApp.view_3Dpatch_checkbox.Value
if isempty(app.vis3Dsurface) || app.is3DChanged
app.vis3Dsurface = []; idxToRemove = [];
for ii = 1:numel(app.VisualizationPlot.Children)
if strcmp(app.VisualizationPlot.Children(ii).Tag,'3D_surface')
idxToRemove = ii; break;
end
end
delete(app.VisualizationPlot.Children(idxToRemove));
if app.segIsoFV_dirty || isempty(app.segIsoFV)
[xx,yy,zz] = meshgrid( ...
(1:size(app.segment,2))*app.pixdim(1), ...
(1:size(app.segment,1))*app.pixdim(2), ...
(1:size(app.segment,3))*app.pixdim(3));
app.segIsoFV = isosurface(xx,yy,zz,smooth3(app.segment));
app.segIsoFV_dirty = false;
end
app.vis3Dsurface = patch(app.VisualizationPlot, app.segIsoFV, ...
'FaceAlpha',0.15,'FaceColor',[0.7 0.7 0.7],'EdgeColor','none', ...
'PickableParts','none','Tag','3D_surface');
app.is3DChanged = 0;
else
app.vis3Dsurface.Visible = 'on';
end
else
if ~isempty(app.vis3Dsurface) && isvalid(app.vis3Dsurface)
app.vis3Dsurface.Visible = 'off';
end
end
if app.VisOptionsApp.view_3DSegpatch_checkbox.Value
if isempty(app.vis3DSegsurface) || app.is3DSegChanged
app.vis3DSegsurface = []; idxToRemove = [];
for ii = 1:numel(app.VisualizationPlot.Children)
if strcmp(app.VisualizationPlot.Children(ii).Tag,'3D_seg_surface')
idxToRemove = ii; break;
end
end
delete(app.VisualizationPlot.Children(idxToRemove));
if app.visSegIsoFV_dirty || isempty(app.visSegIsoFV)
[xx,yy,zz] = meshgrid( ...
(1:size(currSeg,2))*app.pixdim(1), ...
(1:size(currSeg,1))*app.pixdim(2), ...
(1:size(currSeg,3))*app.pixdim(3));
app.visSegIsoFV = isosurface(xx,yy,zz,smooth3(double(currSeg)));
app.visSegIsoFV_dirty = false;
end
app.vis3DSegsurface = patch(app.VisualizationPlot, app.visSegIsoFV, ...
'FaceAlpha',0.15,'FaceColor',[0.7 0.7 0.7],'EdgeColor','none', ...
'PickableParts','none','Tag','3D_seg_surface');
app.is3DSegChanged = 0;
else
app.vis3DSegsurface.Visible = 'on';
end
else
if ~isempty(app.vis3DSegsurface) && isvalid(app.vis3DSegsurface)
app.vis3DSegsurface.Visible = 'off';
end