-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
nifti_studio.m
2758 lines (2388 loc) · 98.4 KB
/
nifti_studio.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 [handles] = nifti_studio(varargin)
% NIfTI Studio:
% A GUI for navigating, visualizing, and editing 3D NIfTI images
% (file types: .nii, .nii.gz, .img/.hdr)
%
% Author:
% Elliot A. Layden, The University of Chicago, 2016-19
%
% Usage:
% To begin, simply type "nifti_studio" into the command line, adding
% any desired name-value pair arguments. Alternatively, simply right-click
% "nifti_studio.m" -> Run. Next, a file selection menu will be
% displayed; select your desired 3D image file, and begin viewing/editing.
%
% Optional Output:
% 'handles', Handles structure for GUI figure, axes, etc.
%
% Optional Inputs (Name-Value Pair Arguments):
% (Note: these can also be loaded within the GUI)
% 'background', filename or path-filename to crossa background image to
% be loaded; can also be loaded image structure
% 'overlay', filename or path-filename to an image to be loaded
% as an overlay; can also be loaded image structure
% 'colorbar', customization: true/false
% 'title_on', customization: true/false
% 'axis_tick_on', customization: true/false
% 'colormap', colormap for main figure (background), specified as
% string, e.g., 'colormap','jet'
% 'axes', an axes graphics object (handle); used to embed a
% NIfTI Studio window within an already present
% figure/axes
% 'apply_header', 1 or 0, denoting whether to apply affine matrix in
% header (Default: 1)
% 'background_caxis', 1x2 vector [cmin, cmax] to scale colors of
% background image
% 'overlay_caxis', 1x2 vector [cmin, cmax] to scale colors of
% overlay image
%
% [Note: if you encounter error messages when loading a file that includes
% "non-orthogonal shearing", this means that applying the affine to the
% image is introducing distortion beyond the tolerance range of NIFTI Tools.
% In this case, try loading the image without applying the affine/header
% info (nifti_studio('apply_header',0); equivalent to using
% load_untouch_nii.m in NIFTI Tools)]
%
% General Features:
% -use up and down arrow keys to navigate slices
% -use the mouse scroll wheel to zoom in or out
% -right click and drag OR Ctrl + left click: pans left/right, up/down
% -click and drag the mouse:
% in Crosshair mode: to obtain coordinates and pixel intensity value at
% the clicked location
% in Drawing mode: draw shapes; for instance, drawing an arc will
% cause the interior of the arc to become filled with color; any closed
% figure will also be filled with color (particularly useful for erasing
% undesirable parts of images like artifacts, or for creating ROIs)
% -can draw to edit background image data, to draw new ROIs which can
% be saved as a separate file from the main image, or to edit loaded
% overlay images (such as a set of ROIs saved from an external program)
% -specify draw color based on image's intensity units (default = 0, i.e.
% erase) for the underlying data or for an overlay, or based on a set of
% pre-defined colors for ROI drawing
% -the transparency of overlays or ROI drawings can be easily adjusted
% -auto-detects screen resolution for positioning of figure window
% -figure can be resized if desired, with objects positioned in normalized
% units
%
% Buttons/Actions (detailed):
% -Click once: draws current color at voxel (default = 0)
% -Click and Drag: upon release, draws line or fills in shape with color
% -Mouse Scroll Wheel (toward computer): zooms in (10 zoom settings: 100%,
% 90%, 80%,...10% of slice area in display window) at current mouse
% location; (away from computer): zooming out at different mouse
% location will also adjust the zoom location
% 's' hotkey saves whichever file is currently being edited
%
% GUI Menus:
% FILE
% -Open: select new file to open as a background or overlay image
% -Close Overlay...: close an open overlay image
% -Save: save a background or overlay image along with any edits made
% using the same filename as was loaded
% -Save As: save a background or overlay image with a new file name
% -Exit (hotkey: 'esc'): exits NIfTI Studio, prompting user to verify
% SELECT
% -select either the background image or a loaded overlay to edit
% -New Overlay...: create a new overlay image
% TOOLS
% -Crosshair (hotkey: 'c'): enables the crosshair tool, which outputs
% voxel location and value when the image is clicked
% -Draw (hotkey: 'd'): enables the drawing tool, which allows edits to
% the selected image (e.g., create new spherical ROIs)
% -Pan (hotkey: 'p'): enables the pan tool, which allows the user to
% click and drag to move the image (adjust axes limits). Note that the
% pan tool can also be accessed while drawing via ctrl + click or right
% click
% EDIT
% -Undo (hotkey: 'u'): undo last action (drawing or orientation change)
% -Redo (hotkey: 'r'): redo actions following calls to undo
% -Go to Slice... (hotkey: 'g'): navigate to a specified slice
% -Revert to Defaults: change display settings back to defaults
% DISPLAY
% -Orientation: change orientation (Coronal, Sagittal, Axial,
% 3D Display, Mosaic of slices)
% -Colorbar (On/Off): turn on/off colorbar
% -Axis Tick (On/Off): turn on/off axis ticks
% -Slice # (On/Off): turn on/off title which displays slice #
% DRAW
% -Select Draw Color: specify an image intensity to use for drawing
% -Shapes: select a shape to draw (No Shape (Manual Trace), Circle,
% Rectangle, Sphere)
% -Propagate through Slices: propagate the most recent drawing through
% specified slices
% -Add Border: specify a # of voxels to create a border within the
% current slice
% -Fill Slice: fill an entire slice with current draw color
% COLORS
% -Colormap: change colormap of the selected image
% -Color Scale: change the color scale (climit) for the selected image
%
% Dependencies:
% NIFTI_tools (Shen, 2005) must be on Matlab's path
% Link: http://www.mathworks.com/matlabcentral/fileexchange/8797-tools-for-nifti-and-analyze-image
% Note that the necessary functions have been included in the
% NIfTI Studio download folder, so no further action is required.
% Note: colorbars and overlays will not function properly for Matlab
% versions prior to 2014b, due to the major graphics update which came in
% 2014b
% Author: Elliot Layden, University of Chicago, 2016-2019
% Contact: elliot.layden@gmail.com
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Load Image and Initialize to Display a Middle Slice:
figure_color = [.2,.2,.2];
axes_color = ones(1,3);
% Identify Function Path and Add Helper Scripts:
script_fullpath = mfilename('fullpath');
[script_path,~,~] = fileparts(script_fullpath);
addpath(genpath(script_path))
% Get Inputs:
inputs = varargin;
parsed_inputs = struct('background',[],'overlay',[],...
'colorbar_on',[],'title_on',[],'axis_tick_on',[],...
'colormap',[],'axes',[],'apply_header',1,...
'background_caxis',[],'overlay_caxis',[]);
poss_input = {'background','overlay','colorbar_on','title_on',...
'axis_tick_on','colormap','axes','apply_header',...
'background_caxis','overlay_caxis'};
% column of internal cells == OR, row of internal cells == AND
input_types = {{'char','file';'struct',''},{'char','file';'struct',''},...
{'logical';'numeric'},{'logical';'numeric'},{'logical';'numeric'},...
{'char'},{'axes'},{'logical';'numeric'},...
{'vector'},{'vector'}};
parsed_inputs = getInputs(inputs, parsed_inputs, input_types);
% If missing background input, clear others:
if isempty(parsed_inputs.background)
parsed_inputs.overlay = [];
parsed_inputs.colormap = [];
parsed_inputs.axes = [];
end
% Determine whether to apply header:
apply_header = parsed_inputs.apply_header;
if apply_header
untouch_nii = false;
elseif ~apply_header
untouch_nii = true;
end
% Initialize Handles & Options:
handles = struct('figure',99.999,'axes',99.999,'images',99.999);
handles.axes = {99.999}; handles.images = {99.999};
% Initialize Figure (auto-detect screen size):
set(0,'units','pixels');
screen_res = get(0,'ScreenSize');
figure_pos = [.25*screen_res(3), .065*screen_res(4), ...
.5*screen_res(3), .86*screen_res(4)];
if any(figure_pos<=0) % avoid ScreenSize errors
figure_pos = [342,50,683,660];
screen_res = [1,1,(figure_pos(3:4)./[.5,.86])];
end
if isempty(parsed_inputs.axes) % if no axes supplied
handles.figure = figure('Position',figure_pos,'MenuBar','none',...
'Name','NIfTI Studio','NumberTitle','off','Color',figure_color,...
'Visible','off','doublebuffer','on','Interruptible','off');
else
handles.figure = get(parsed_inputs.axes,'Parent');
end
figure(handles.figure)
% Intialize GUI Data:
selectedImage = 1;
nOverlays = 0; % global counter that never decrements (even when delete previous overlay, numbering continues based on this)
if ~isempty(parsed_inputs.axes)
ax_pos_input = get(parsed_inputs.axes,'Position');
end
fig_height = figure_pos(4);
screen_mid_x = .5*screen_res(3);
if isempty(parsed_inputs.axes)
handles.axes{selectedImage} = 16.48382;
else
handles.axes{selectedImage} = parsed_inputs.axes;
end
% Main Data Storage:
imageData = {0}; alphaData = {0};
cmin = {0}; cmax = {0};
img = [];
fullPaths = {[]}; % stores full paths of background and overlay images
origin = [];
physical_units = [];
units = 'physical';
filename = []; fpath = []; aspect_ratio = []; fig_width = []; dimperm = [];
draw_on = false; pan_on = false;
window_name = []; dim = []; pixdim = []; voxSize = []; xwidth = []; yheight = [];
xdim = []; ydim = []; zdim = []; middle_slice = [];
curr_slice = []; curr_drawing = [];
xind = []; yind = [];
xmax = []; xmin = []; ymax = []; ymin = [];
ax_xlim = []; ax_ylim = [];
x_slice = []; y_slice = []; z_slice = [];
in_motion = false;
draw_color = 1;
erase_draw = false;
idx_draw = [];
scroll_count = 0;
launch_mosaic_string = 'Mosaic (Beta)';
launch_3d_string = '3D Display';
% Initialize undo/redo:
undoNum = 0; undoLimit = 10;
undoCache = struct('selectedImage', [], 'action', [], ...
'orientation', [], 'idx', [], 'color', [], 'alpha', []);
redoCache = struct('selectedImage', [], 'action', [], ...
'orientation', [], 'idx', [], 'color', [], 'alpha', []);
poss_ind = []; save_points = [];
n_ticks_x = 10; n_ticks_y = 10;
xticks = []; yticks = [];
% Menu Handles:
orientation_labels = {'Coronal', 'Sagittal', 'Axial',...
launch_3d_string, launch_mosaic_string}; % 'Mosaic'
menu_orientations = zeros(1,length(orientation_labels));
menu_slice_number = []; menu_colorbar = []; menu_axis_tick = [];
% Axes Positions:
ax_pos_all_on = [.09, .04, .8, .92]; % All On
ax_pos_all_off = [0, 0, 1, 1]; % All Off
ax_pos_no_title = [.09, .04, .8, .95]; % No Title
ax_pos_no_colorbar = [.09, .04, .88, .92]; % No Colorbar
ax_pos_no_tick = [0, 0, .88, .95]; % No Tick
ax_pos_title_only = [0, 0, 1, .95]; % Title only
ax_pos_colorbar_only = [0, 0, .88, 1];% Colorbar only
ax_pos_tick_only = [.09, .04, .88, .95]; % Tick Only
colorbar_pos = [.927, ax_pos_all_on(2), 0.0390, ax_pos_all_on(4)];
curr_axis_pos = ax_pos_all_on;
x_ax_percent = curr_axis_pos(3);
y_ax_percent = curr_axis_pos(4);
prev_state = 1; curr_state = 1; % various combo's of axes objects
% Colormap & Overlay Settings:
colormap_n = 200; % Number of distinct colors in the current colormap
n_colorbar_ticks = 10; % number of ticks on colorbar
% Colormaps & Colorbars:
h_colorbar = 20.19347;
colorMapStr = {'gray','jet'};
colormap_opts = {'gray','jet','hot','cool','hsv','bone','colorcube','copper',...
'spring','summer','winter','pink'};
colormaps{selectedImage} = colormap(eval([colorMapStr{selectedImage},'(',num2str(colormap_n),')']));
colorscaleType = {1, 2}; % (1) Slice min/max, (2) Global min/max, (3) Custom
% Opacity / alpha
alpha_opts = {'Opaque','90%','80%','70%','60%','50%','40%','30%',...
'20%','10%','Invisible'};
alpha_values = 1:-.1:0;
alphaValue = {1, .6}; % overlay transparency (default: 60%)
% Drawing ROIs
curr_drawing = [];
shape = 0; shape_ind = zeros(2,2); sphere_radius = 1;
shape_coords = zeros(64,2);
prev_shape_colors = zeros(64,1);
prev_alpha = [];
% Other:
customizable = {'colorbar_on','title_on','axis_tick_on',...
'extensions','last_nav_dir','colorMapStr'};
first_dir = pwd; last_nav_dir = pwd;
extensions = {'*.img';'*.nii';'*.nii.gz'};
slice_orientation = 3; % default = z-dim
h_title = 10.48487; num_voxels_border = 0;
scroll_zoom_equiv = [1,.9,.8,.7,.6,.5,.4,.3,.2,.1];
% Set user interface callback functions:
set(handles.figure,'WindowKeyPressFcn',@keypress_callback);
% Don't turn on click function if embedded graphic in user spec axes:
if isempty(parsed_inputs.axes)
set(handles.figure,'WindowButtonDownFcn',@cursor_click_callback);
end
set(handles.figure,'WindowScrollWheelFcn',@scroll_zoom_callback);
if isempty(parsed_inputs.axes)
set(handles.figure,'CloseRequestFcn',@closereq_callback)
else
set(handles.figure,'CloseRequestFcn',@closereq_no_dlg)
end
% Get Settings:
succeeded = getSettings; % extracts custom settings from .txt if available
if ~isempty(parsed_inputs.title_on)
title_on = parsed_inputs.title_on;
elseif ~succeeded
title_on = true;
end
if ~isempty(parsed_inputs.axis_tick_on)
axis_tick_on = parsed_inputs.axis_tick_on;
elseif ~succeeded
axis_tick_on = true;
end
if ~isempty(parsed_inputs.colorbar_on)
colorbar_on = parsed_inputs.colorbar_on;
elseif ~succeeded
colorbar_on = true;
end
% Background: Get Input Filename & Load
if isempty(parsed_inputs.(poss_input{1}))
status = openNewBackground;
if ~status; return; end
elseif ischar(parsed_inputs.(poss_input{1}))
[fpath,filename,ext] = fileparts(parsed_inputs.(poss_input{1}));
filename = [filename,ext];
sort_exts(fpath,filename);
load_img('char');
elseif isstruct(parsed_inputs.(poss_input{1}))
load_img('struct');
end
%% Create Menu Items:
if isempty(parsed_inputs.axes)
% FILE
file_menu = uimenu(handles.figure,'Label','File');
% OPEN
open_menu = uimenu(file_menu,'Label','Open');
uimenu(open_menu,'Label','Background Image','Callback',{@openNewBackground,1});
uimenu(open_menu,'Label','Overlay Image','Callback',@openNewOverlay);
uimenu(open_menu,'Label','New Overlay','Callback',@createOverlay);
% CLOSE
close_overlays_menu = uimenu(file_menu,'Label','Close Overlay...');
h_close = [];
% SAVE
save_menu = uimenu(file_menu,'Label','Save');
uimenu(save_menu,'Label','Save Background Image','Callback',{@save_callback,1});
uimenu(save_menu,'Label','Save Current Overlay','Callback',{@save_callback,2});
% SAVE AS
save_as_menu = uimenu(file_menu,'Label','Save As');
uimenu(save_as_menu,'Label','Save Background Image As','Callback',{@saveas_callback,1});
uimenu(save_as_menu,'Label','Save Current Overlay As','Callback',{@saveas_callback,2});
uimenu(file_menu,'Label','Exit ''esc''','Callback',@closereq_callback);
% SELECT
select_menu = uimenu(handles.figure,'Label','Select');
h_image(1) = uimenu(select_menu,'Label','Background Image',...
'Checked','on','Callback',{@changeSelection,1});
h_new_image = uimenu(select_menu,'Label','New Overlay...',...
'Callback',@createOverlay);
% TOOLS
tools_menu = uimenu(handles.figure,'Label','Tools');
tool_crosshair = uimenu(tools_menu,'Label','Crosshair ''c''',...
'Callback',@crosshair_callback, 'Checked','on');
tool_draw = uimenu(tools_menu,'Label','Draw ''d''',...
'Callback',@draw_callback);
% tool_zoom = uimenu(tools_menu,'Label','Zoom ''z''',...
% 'Callback',@zoom_callback);
tool_pan = uimenu(tools_menu,'Label','Pan ''p''',...
'Callback',@pan_callback);
% EDIT
edit_menu = uimenu(handles.figure,'Label','Edit');
uimenu(edit_menu,'Label','Undo ''u''',...
'Callback',@undoCallback);
uimenu(edit_menu,'Label','Redo ''r''',...
'Callback',@redoCallback);
uimenu(edit_menu,'Label','Go to Slice... ''g''',...
'Callback',@goToSlice);
uimenu(edit_menu,'Label','Go to Origin... ''o''',...
'Callback',@goToOrigin);
uimenu(edit_menu,'Label','Revert to Defaults','Callback',@revert_defaults);
end
% DISPLAY
display_opts_menu = uimenu(handles.figure,'Label','Display');
orient_menu = uimenu(display_opts_menu,'Label','Orientation');
for ixx = 1:length(orientation_labels)
menu_orientations(ixx) = uimenu(orient_menu,'Label',...
orientation_labels{ixx},'Checked','off',...
'Callback',@reorient_callback);
end
set(menu_orientations(3),'Checked','on');
% Units:
menu_units = uimenu(display_opts_menu,'Label','Units');
h_units(1) = uimenu(menu_units,'Label','Physical','Checked','on',...
'Callback', @changeUnits);
h_units(2) = uimenu(menu_units,'Label','Voxel','Checked','off',...
'Callback', @changeUnits);
if isempty(parsed_inputs.axes)
if colorbar_on
menu_colorbar = uimenu(display_opts_menu,'Label','Colorbar',...
'Checked','on','Callback',@colorbar_callback);
else
menu_colorbar = uimenu(display_opts_menu,'Label','Colorbar',...
'Checked','off','Callback',@colorbar_callback);
end
if axis_tick_on
menu_axis_tick = uimenu(display_opts_menu,'Label','Axis Tick',...
'Checked','on','Callback',@axis_tick_callback);
else
menu_axis_tick = uimenu(display_opts_menu,'Label','Axis Tick',...
'Checked','off','Callback',@axis_tick_callback);
end
if title_on
menu_slice_number = uimenu(display_opts_menu,'Label','Slice #',...
'Checked','on','Callback',@title_toggle_callback);
else
menu_slice_number = uimenu(display_opts_menu,'Label','Slice #',...
'Checked','off','Callback',@title_toggle_callback);
end
% DRAW
draw_menu = uimenu(handles.figure,'Label','Draw');
h_color_menu = uimenu(draw_menu,'Label','Select Draw Color');
h_color = zeros(1,11);
h_color(1) = uimenu(h_color_menu,'Label','Erase',...
'Callback',{@change_color_callback, 0});
for j = 2:10
h_color(j) = uimenu(h_color_menu,'Label',num2str(j-1),...
'Callback',{@change_color_callback, j-1});
end
set(h_color(2), 'Checked', 'on')
h_color(11) = uimenu(h_color_menu,'Label','Custom',...
'Callback',{@change_color_callback, 10});
h_shapes = zeros(1,4);
h_shapes_menu = uimenu(draw_menu,'Label','Shapes');
h_shapes(1) = uimenu(h_shapes_menu,'Label','No Shape (Manual Trace)',...
'Checked','on','Callback',{@draw_shapes_callback, 0});
h_shapes(2) = uimenu(h_shapes_menu,'Label','Circle','Callback',{@draw_shapes_callback,1});
h_shapes(3) = uimenu(h_shapes_menu,'Label','Rectangle','Callback',{@draw_shapes_callback,2});
h_shapes(4) = uimenu(h_shapes_menu,'Label','Sphere','Callback',{@draw_shapes_callback,3});
uimenu(draw_menu,'Label','Propagate last draw through slices','Callback',@propagate_draw_callback);
uimenu(draw_menu,'Label','Add Border','Callback',@add_border_callback);
uimenu(draw_menu,'Label','Fill Slice','Callback',@apply2whole_slice_callback);
% COLOR
color_menu = uimenu(handles.figure, 'Label', 'Colors');
% Colormap / cmap
colormap_menu = uimenu(color_menu,'Label','Colormap');
h_colormap_menu = zeros(1, length(colormap_opts));
for j = 1:length(colormap_opts)
h_colormap_menu(j) = uimenu(colormap_menu, ...
'Label', colormap_opts{j}, ...
'Callback', {@colormap_callback, j});
end
% Colorscale / caxis
h_colorscale_menu = zeros(1,3);
colorscale_menu = uimenu(color_menu,'Label','Color Scale');
h_colorscale_menu(1) = uimenu(colorscale_menu,...
'Label','Slice Min/Max','Callback',{@colorscale_callback, 1},...
'Checked','on');
h_colorscale_menu(2) = uimenu(colorscale_menu,...
'Label','Global Min/Max','Callback',{@colorscale_callback, 2});
h_colorscale_menu(3) = uimenu(colorscale_menu,...
'Label','Custom...','Callback',{@colorscale_callback, 3});
% Opacity / alpha
opacity_menu = uimenu(color_menu,'Label','Opacity');
h_opacity_menu = zeros(1, length(alpha_opts));
for j = 1:length(alpha_opts)
h_opacity_menu(j) = uimenu(opacity_menu,...
'Label', alpha_opts{j},'Callback', {@opacity_callback, j});
end
% if overlay_present
% set(h_opacity_menu(strcmp(alpha_opts, alphaValue{2})), 'Checked','on')
% else
set(h_opacity_menu(1), 'Checked','on')
set(opacity_menu, 'Visible','off')
% end
end
%% Customizations
% Must run to initialize axes etc., prior to the subsequent lines
updateImage
% Add Overlays If Requested:
if ~isempty(parsed_inputs.overlay)
switch class(parsed_inputs.overlay)
case 'char'
openNewOverlay([], [], 'char');
case 'struct'
openNewOverlay([], [], 'struct');
otherwise
if isnumeric(parsed_inputs.overlay)
openNewOverlay([], [], 'matrix');
end
end
end
% Adjust colormap of background image based on input
selectedImageHolder = selectedImage;
selectedImage = 1;
if ~isempty(parsed_inputs.colormap)
if ismember(parsed_inputs.colormap, colormap_opts)
colormap_callback([], [], find(strcmp(parsed_inputs.colormap, colormap_opts)))
else
warning('Invalid ''colormap'' input.')
end
else
colormap_callback([], [], find(strcmp(colorMapStr{selectedImage}, colormap_opts)))
end
selectedImage = selectedImageHolder;
set(handles.figure,'Visible','on'); % Make Visible
% Adjust CAXES if specified:
if ~isempty(parsed_inputs.background_caxis)
if parsed_inputs.background_caxis(2)~=parsed_inputs.background_caxis(1) && parsed_inputs.background_caxis(2)>parsed_inputs.background_caxis(1)
cmin{1} = parsed_inputs.background_caxis(1);
cmax{1} = parsed_inputs.background_caxis(2);
colorscaleType{1} = 3;
% Adjust colorscale menu checkmarks:
set(h_colorscale_menu(2), 'Checked','off') % default
set(h_colorscale_menu(3), 'Checked','on') % Custom
else
warning('Invalid background color axis specification. Ignoring inputs.')
return;
end
refresh_img = 0;
updateImage;
end
if ~isempty(parsed_inputs.overlay_caxis)
if parsed_inputs.overlay_caxis(2)~=parsed_inputs.overlay_caxis(1) && parsed_inputs.overlay_caxis(2)>parsed_inputs.overlay_caxis(1)
cmin{2} = parsed_inputs.overlay_caxis(1);
cmax{2} = parsed_inputs.overlay_caxis(2);
colorscaleType{2} = 3;
% Adjust colorscale menu checkmarks:
set(h_colorscale_menu(2), 'Checked','off') % default
set(h_colorscale_menu(3), 'Checked','on') % Custom
else
warning('Invalid background color axis specification. Ignoring inputs.')
return;
end
refresh_img = 0;
updateImage;
end
repositionAxes(1);
% Turn on default tool 'crosshair':
crosshair_callback;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Helper Functions:
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Load Background Image:
function load_img(img_type)
switch img_type
case 'struct'
try
img = parsed_inputs.(poss_input{1});
try
fpath = img.fileprefix;
[~,filename,~] = fileparts(fpath);
catch
filename = 'Image Structure';
end
catch
error('Error loading image structure. Check fields and retry or load through GUI.')
end
case 'char'
fullPaths{1} = fullfile(fpath, filename);
if untouch_nii
img = load_untouch_nii(fullPaths{1});
else
try
img = load_nii(fullPaths{1});
catch
img = load_untouch_nii(fullPaths{1});
untouch_nii = true;
warning('Non-orthogonal shearing detected in affine matrix. Image loaded without applying affine.')
end
end
end
% Determine voxel units & origin:
try
origin = img.hdr.hist.originator(1:3);
switch bitand(img.hdr.dime.xyzt_units, 7) % see xform_nii.m, extra_nii_hdr.m
case 1, physical_units = 'm';
case 2, physical_units = 'mm';
case 3, physical_units = 'microns';
otherwise, physical_units = '';
end
catch
physical_units = '';
origin = img.hdr.dime.dim(2:4)/2;
warning('Failed to retrieve voxel units.')
end
if any(origin==0)
origin = img.hdr.dime.dim(2:4)/2;
end
% Change selected image back to background:
if selectedImage ~= 1
changeSelection([], [], 1)
end
% Close any open overlays:
selectedImage = 1;
nOverlays = 0; % reset
if length(imageData)>1
for i = 2:length(imageData)
closeOverlay([], [], i)
end
end
% Clear overlay menu items if present
if exist('h_image', 'var') && numel(h_image) > 1
h_image = h_image(1);
end
if exist('h_close', 'var') && numel(h_close) > 1
h_close = h_close(1);
end
% Parse image input
window_name = ['NIfTI Studio: ',filename];
set(handles.figure,'Name',window_name);
dim = img.hdr.dime.dim;
pixdim = img.hdr.dime.pixdim;
voxSize = pixdim(2:4);
xwidth = dim(2)*pixdim(2);
yheight = dim(3)*pixdim(3);
imageData = {single(img.img)}; % conversion may enhance refresh speed
imageData{1} = permute(imageData{1},[2,1,3]); % Match SPM View
voxSize = voxSize([2,1,3]); % d=0
origin = origin([2,1,3]);
[xdim, ydim, zdim] = size(imageData{1});
middle_slice = round(zdim/2);
curr_slice = middle_slice;
xind = xdim:-1:1;
yind = 1:ydim;
slice_orientation = 3; % default: Z-dim
cmin = {min(imageData{1}(:))};
cmax = {max(imageData{1}(:))};
if cmin{1}==cmax{1}; cmax{1} = cmin{1} + 1; end
xmax = max(xind); xmin = min(xind);
ymax = max(yind); ymin = min(yind);
ax_xlim = [1,numel(yind)]; ax_ylim = [1,numel(xind)];
% Clear previous axes & images:
for i = 1:numel(handles.axes)
if isgraphics(handles.axes{1},'axes'); cla(handles.axes{1}); end
if ishandle(handles.images{1}); delete(handles.images{1}); end
end
% Reset
scroll_count = 0;
% Reset undo's:
undoNum = 0;
undoCache = struct('selectedImage', [], 'action', [], ...
'orientation', [], 'idx', [], 'color', [], 'alpha', []);
redoCache = [];
% Determine possible combinations of x,y indices:
poss_ind = zeros(xdim*ydim,2); count = 0;
for ix = 1:xdim
for jx = 1:ydim
count = count + 1;
poss_ind(count,:) = [ix,jx];
end
end
end
% Load Overlay Image:
function openNewOverlay(~, ~, load_type)
if nargin<3
load_type = 'char';
end
fullpath = [];
switch load_type
case 'char'
if nargin < 3
% Get input filename:
cd(last_nav_dir);
[overlayName, overlay_path] = uigetfile(extensions,...
'Select Overlay Image:','MultiSelect','off');
cd(first_dir);
elseif nargin==3
[overlay_path, overlayName, ext] = fileparts(parsed_inputs.(poss_input{2}));
overlayName = [overlayName, ext];
end
if ischar(overlayName)
fullpath = fullfile(overlay_path, overlayName);
% Remember Extension Chosen:
if ~isempty(overlay_path)
sort_exts(overlay_path,overlayName)
end
if untouch_nii
overlay1_img = load_untouch_nii(fullpath);
else
overlay1_img = load_nii(fullpath);
end
else
return
end
case 'struct'
overlayName = 'Overlay 1';
try
overlay1_img = parsed_inputs.(poss_input{2});
catch
error('Error loading overlay image. Check fields and retry or load through GUI.')
end
case 'matrix'
overlayName = 'Overlay 1';
overlay1_img = img;
overlay1_img.img = parsed_inputs.(poss_input{2});
end
% Before update, go to default orientation:
save_orientation = [];
if slice_orientation==1
save_orientation = 1;
reorient_callback(menu_orientations(3)) % revert to original orientation
elseif slice_orientation==2
save_orientation = 2;
reorient_callback(menu_orientations(3)) % revert to original orientation
end
% Extract & store image
if ~all(size(overlay1_img.img)==dim(2:4))
error('Error: Overlay dimensions do not match original image.');
end
imageData{end + 1} = single(overlay1_img.img); % conversion may enhance refresh speed
selectedImage = numel(imageData);
nOverlays = nOverlays + 1;
fullPaths{selectedImage} = fullpath; % add filepath for image saving
% Permute dimensions to match:
imageData{selectedImage} = permute(imageData{selectedImage},[2,1,3]);
alphaValue{selectedImage} = .6;
alphaData{selectedImage} = single(zeros(size(imageData{selectedImage})));
use_idx = ((imageData{selectedImage}(:)~=0) + (~isnan(imageData{selectedImage}(:))))==2;
alphaData{selectedImage}(use_idx) = alphaValue{selectedImage};
% Add new menu item:
incrementOverlayMenus(overlayName)
% Calculate Image Color Indices
colorscaleType{selectedImage} = 2; % Global min/max (default for overlays)
cmin{selectedImage} = min(imageData{selectedImage}(:));
cmax{selectedImage} = max(imageData{selectedImage}(:));
if cmin{selectedImage} == cmax{selectedImage}
cmax{selectedImage} = cmax{selectedImage} + 1;
end
% Create new axes:
handles.axes{selectedImage} = axes('parent', handles.figure, 'Visible','off','YDir','reverse'); % must remain invisible
handles.axes{selectedImage}.CLim = [cmin{selectedImage}, cmax{selectedImage}];
% Add new colormap:
colormap_callback([], [], 2)
% Handle several uimenu and colobar changes:
changeSelection([], [], selectedImage)
% Return to Original Orientation if Changed:
if ~isempty(save_orientation)
reorient_callback(menu_orientations(save_orientation)) % have to have two inputs, see line 1047
end
% Update Figure:
updateImage
updateColormap
end
function createOverlay(~,~,~)
% Create new entries in imageData, alphaData, etc.
selectedImage = numel(imageData) + 1;
nOverlays = nOverlays + 1;
% Image & Opacity data
imageData{selectedImage} = single(nan(size(imageData{1})));
alphaData{selectedImage} = single(zeros(size(imageData{1})));
alphaValue{selectedImage} = .6;
fullPaths{selectedImage} = [];
% Color mapping
colorscaleType{selectedImage} = 2; % Global min/max (default for overlays)
cmin{selectedImage} = 0;
cmax{selectedImage} = 1;
% Create new axes:
handles.axes{selectedImage} = axes('parent', handles.figure, 'Visible','off','YDir','reverse'); % must remain invisible
handles.axes{selectedImage}.CLim = [cmin{selectedImage}, cmax{selectedImage}];
% Add new colormap:
colormap_callback([], [], 2)
% Add additional uimenu's
incrementOverlayMenus
% Handle several uimenu and colobar changes:
changeSelection([], [], selectedImage)
updateImage
end
function incrementOverlayMenus(overlayName)
% Remove New Overlay menu item, then regenerate it at the end of list:
if exist('h_new_image','var') && ishandle(h_new_image)
delete(h_new_image)
end
% Add new SELECT menu:
if nargin==0 || isempty(overlayName)
h_image(end + 1) = uimenu(select_menu,'Label',...
sprintf('Overlay %1g', nOverlays),'Callback',...
{@changeSelection, nOverlays + 1});
else
h_image(end + 1) = uimenu(select_menu,'Label',...
overlayName,'Callback',...
{@changeSelection, nOverlays + 1});
end
for i = 1:length(h_image)
if ishandle(h_image(i))
set(h_image(i),'Checked','off') % Uncheck all
end
end
set(h_image(end),'Checked','on') % Check new
% Re-make New Overlay button in SELECT menu:
h_new_image = uimenu(select_menu,'Label','New Overlay...',...
'Callback',@createOverlay);
% Add new CLOSE overlay menu:
if nargin==0 || isempty(overlayName)
if ~isempty(h_close)
h_close(end + 1) = uimenu(close_overlays_menu,'Label',...
sprintf('Overlay %g', nOverlays),'Callback',{@closeOverlay, nOverlays + 1});
else
h_close(2) = uimenu(close_overlays_menu,'Label',...
sprintf('Overlay %g', 1),'Callback',{@closeOverlay, 2}); % start at index 2 to match h_image
end
else
if ~isempty(h_close)
h_close(end + 1) = uimenu(close_overlays_menu,'Label',...
overlayName,'Callback',{@closeOverlay, nOverlays + 1});
else
h_close(2) = uimenu(close_overlays_menu,'Label',...
overlayName,'Callback',{@closeOverlay, 2}); % start at index 2 to match h_image
end
end
end
function sort_exts(path1,name1)
last_nav_dir = path1;
[~,~,ext] = fileparts(name1);
for ix = 1:3
if ~isempty(strfind(extensions{ix},ext))
type = ix;
others = setdiff(1:3,ix);
break;
end
end
extensions = extensions([type,others]);
end
function resizeFigure
aspect_ratio = (xwidth/x_ax_percent)/(yheight/y_ax_percent);
fig_width = aspect_ratio*fig_height;
figure_pos(1) = max(screen_res(1)+8, screen_mid_x-(.5*fig_width));
figure_pos(3) = min(screen_res(3)-figure_pos(1)-7, fig_width);
handles.figure.Position = figure_pos;
end
function success = getSettings
listing = dir(fullfile(script_path, 'helpers', 'nifti_studio_settings.txt'));
if isempty(listing)
disp('No customized settings file found: missing file ''nifti_studio_settings.txt''.')
success = false;
return
end
gui_settings = importdata(fullfile(script_path, 'helpers', listing(1).name));
for ix1 = 1:length(gui_settings)
ind = strfind(gui_settings{ix1},'=');
eval([customizable{ix1}, '=[', gui_settings{ix1}(ind+1:end),'];']);
end
if ~isdir(last_nav_dir); last_nav_dir = pwd; end %#ok
success = true;
end
function write_settings
% Change Settings Data / Convert to char array:
gui_settings = cell(6,1);
for ix1 = 1:3
setting1 = eval(customizable{ix1});
if length(setting1)==1
gui_settings{ix1} = [customizable{ix1},'=',num2str(setting1),';'];
else
gui_settings{ix1} = [customizable{ix1},'=1;'];
end
end
exts = eval(customizable{4});
gui_settings{4} = [customizable{4},'={''',exts{1},''';''',exts{2},''';''',exts{3},'''};'];
gui_settings{5} = [customizable{5},'=''',eval(customizable{5}),''';'];
gui_settings{6} = [customizable{6},'={''',colorMapStr{1},'''};'];
gui_settings = char(gui_settings);
% Write as Text File:
try
fileID = fopen(fullfile(script_path, 'helpers', 'nifti_studio_settings.txt'),'w');
for ix1 = 1:6
fprintf(fileID,'%s\r\n',gui_settings(ix1,:));
end
fclose(fileID);
catch
warning('Failed to cache settings.')
end
end
function revert_defaults(~,~,~)
% Default display options
colorbar_on = 1;
title_on = 1;
axis_tick_on = 1;
set(menu_colorbar,'Checked','on')
set(menu_axis_tick,'Checked','on')
set(menu_slice_number,'Checked','on')
extensions = {'*.img';'*.nii';'*.nii.gz'};
last_nav_dir = first_dir;
% Change colormaps to defaults
save_selected = selectedImage;
selectedImage = 1;
colorMapStr{1} = 'gray';
colormap_callback([], [], 1)
if length(colorMapStr)>1
for k = 2:length(colorMapStr)
selectedImage = k;
colorMapStr{k} = 'jet';
colormap_callback([], [], 2)
end
end
selectedImage = save_selected;
refresh_img = true;
updateImage
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Callback Functions:
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% File Menu:
% Exit Request Callback
function closereq_callback(~,~,~)
selection = questdlg('Are you sure you want to exit NIfTI Studio?','Exit NIfTI Studio',...
'Yes','No','Yes');
switch selection