-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathImageServer.m
More file actions
1850 lines (1519 loc) · 68.7 KB
/
ImageServer.m
File metadata and controls
1850 lines (1519 loc) · 68.7 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 ImageServer < handle
% IMAGESERVER is a class capable of loading in multidimensional image
% data from various sources. Data can be 2D images, 3D .tif stacks, and
% video data of .avi and .mp4 formats. Aside from files or folders,
% sources of data can also be webcams or image acquisition devices like
% sCMOS cameras connected to the computer via a capture card. Devices will
% appear as long as the user has necessary drivers installed and the
% device firmware is compatible with MATLAB's image acquisition toolbox.
% The general flow in using this class is to first set the source of your
% data, then call the read method to update the 2D image currently being
% viewed. If the user would like to set a crop to have less data loaded up,
% this can be implemented after the source is set.
%
% NOTE: For a future version - If the user has bioformats, server will
% leverage the bioformats package to load in commercial microscope image
% formats.
%
% William A. Ramos, Kumar Lab @MBL February 2024
% email: wramos@mbl.edu
properties (Access = private)
% Image related
Source % Source determines how additional images are passed into the image server. Can be a numerical array from workspace, image datastore, a file,
variable % When source is a matfile object, this has the variable name that holds the data
fidx % When source is an imagedata store or live folder, this refers to the file index
BFReader % Need to initialize the Bio Formats reader object to configure acceptable file formats
% Options
lazyloading = true % Loads portions of data on the fly for memory efficiency at cost of speed. Accounts for systems with less RAM
end
properties (GetAccess = public, SetAccess = private)
% Parent GUI
GUI
% Image
Stack % Holds full ND image array if lazyloading is off or user has directly passed the array into the class
Slice % The current slice being viewed
newstackreq % New stack requested - true when user has changed index 4 or 5 which requires loading a new stack
% Image metadata - persistent and dependent on source
filefolder % Path to file
filename % Image file name (if loaded from filepath / imds) OR variable name (if loaded via matfile object)
fileext % Extension of file
% Dimension sizes metadata - persistent and dependent on source
mrows % Number of rows in image (y dim)
ncols % Number of columns in image (x dim)
numslices % Number of z slices in image stack
numframes % Number of timepoints
numfiles % Number of files in the datastore/folder. Updates if user is imaging as new files are written (live folder source type)
channels % Number of channels - bioformats / workspace array compatible
% 2D Slice Indexing
slice % Z index - D3 - slice currently loaded
framenum % T index - D4 - timepoint currently loaded
channel % C index - D5 - channel currently loaded - only compatible with bioformats and numerical arrays
dim4idx % T/F index - D4 - Represents data's 4th dimension. Can either be time or file index, depending on source type
% Crop ROI
croprows % crop ROI coordinates (D1 - rows) - row vector of image's row indices used for crop
cropcols % crop ROI coordinates (D2 - cols) - row vector of image's col indices used for crop
% Acceptable formats - can eventually include the BIOFORMATS /
% commercial formats as well
filefilt = {'*.mat; *.png; *.jfif; *.jpg; *.jpeg; *.tif; *.tiff; *.avi; *.mp4; *.mpg; *.mpeg',...
'All Array Data Formats (*.mat, *.png, *.jfif, *.jpg, *.jpeg, *.tif, *.tiff, *.avi, *.mp4, *.mpg, *.mpeg)';...
'*.png; *.jfif; *.jpg; *.jpeg; *.tif; *.tiff',...
'2D Images (*.png, *.jfif, *.jpg, *.jpeg, *.tif, *.tiff)';...
'*.mat',...
'MATLAB Data (*.mat)';...
'*.tif; *.tiff',...
'3D Image Stack (*.tif, *.tiff)';...
'*.avi; *.mp4; *.mpg; *.mpeg',...
'Videos (*.avi, *.mp4, *.mpg, *.mpeg)'};
% Video reader formats
vidformats
% BioFormats file extensions property - used if user has BF
bffileexts
% BioFormats integration - if user has bfmatlab, the following
% formats are also compatible with this class:
% https://bio-formats.readthedocs.io/en/v7.2.0/formats/dataset-table.html
end
properties (Dependent)
fullFID % returns the full file ID (filepath)
mrowscrop % queries y dimension size based on the crop coordinates
ncolscrop % queries x dimension size based on the crop coordinates
sizes % queries data source dimensionality/size. Dimension sizes will depend on the source type - will return a vector when queried
dataloaded % queries whether data is loaded in the server - returns a logical flag (true if data loaded)
isstacknavigable % queries whether user can navigate dimension 3 of data by checking dimensionality of data source - returns a logical flag (true if navigable)
istimenavigable % queries whether user can navigate dimension 4 of data by checking dimensionality of data source - returns a logical flag (true if navigable)
Classmethods % queries the class methods the user can use - returns cell array of list of publicly available class methods
Classproperties % queries the properties the user can use - returns cell array of list of publicly available class properties
Datasources % queries available options for data sources
dim4 % queries either time or file index depending on which is larger and data source type. Useful for bounds checking
end
methods(Access = public)
%% Initialization and Settings
function obj = ImageServer(fid)
% IMAGESERVER Constructor. Can take input to instatiate with
% data immediately loaded up.
%
% INPUTS:
% fid (optional) - filepath, folder path, or numerical array.
% Loads data according to input type
if nargin == 1
obj.LoadImage(fid)
end
% Video reader compatible formats
vf = VideoReader.getFileFormats;
obj.vidformats = {vf.Extension};
% Check to see that user has bioformats
if obj.UserHasBF
% Appending the BF formats
obj.BFReader = bfGetReader;
bfformats = bfGetFileExtensions;
obj.filefilt = vertcat(bfformats(1,:), obj.filefilt, bfformats(2:end,:));
obj.bffileexts = GetAllBFExtensions;
end
end
function SetGUIHandle(obj, f)
% SETGUIHANDLE allows user to set a GUI uifigure handle to
% enable certain prompt functionality. Otherwise, terminal line
% interactivity is used by default.
if isa(f, 'matlab.ui.Figure')
obj.GUI = f;
else
msg = 'Input was not a uifigure.';
msg = [msg newline 'No GUI figure handle was passed' ...
'into the class.'];
warning(msg)
end
end
function LoadImage(obj, s)
% obj.LOADIMAGE(s)
%
% SUMMARY:
% LOADIMAGE will load a new image into the class. The input can
% be a filepath for a 2D image or 3D stack, a path to a folder
% that will then become an imagedatastore, or an array which is
% then passed to the class. If no arguments are passed, then
% the user will be prompted to select file(s) to load in via a
% GUI window.
%
% INPUTS:
% s (optional) a folder/filepath or image array
% Intended Datatype: string, char, uint8, uint16, single, double
%
% OUTPUTS:
% None. The class will update its ImageSlice and ImageStack
% properties to reflect the newly loaded in image.
if nargin < 2
s = [];
end
% Resetting crop properties to ensure full loading of images
obj.ResetIndices % Resets indices to 1 for dimensions 3-4
if ischar(s) || isstring(s)
% Creates image datastore or loads individual image
obj.LoadFromString(s)
elseif isnumeric(s) && ~isempty(s)
% Array variable passed to method
obj.LoadFromArray(s)
elseif isempty(s)
% Will load new image via ui prompt window
obj.SetupFileSource(obj.filefolder);
elseif iscell(s)
obj.SetupMultiFileSource(s)
end
% Checks to ensure data is properly formated in terms of data
% type and dimensionality
obj.CheckType
obj.CheckDims
end
function ResetIndices(obj)
% RESETINDICES will set all relevant indices to 1 to ensure
% the next loaded image is the first image in the data source.
% All data that is loaded in will have 1 slice and 1 timepoint
% by default. This is used as initialization of the values
% which will be adjusted if greater than 1 and enables indexing
% in the branching of the read function for different data
% source types.
obj.slice = 1;
obj.framenum = 1;
obj.fidx = 1;
obj.channel = 1;
obj.dim4idx = 1;
obj.channel = 1;
end
function Reset(obj)
% obj.RESET
%
% SUMMARY:
% RESET will reset indices, crop coordinates and reload the
% first image if a source is still set. This will also reenable
% lazy loading, helping to reduce memory load upon resetting.
% Set defaults
obj.ResetIndices
% Resetting crop
obj.ResetCropCoords
% Reenable lazy loading by default
obj.SetLazyLoading(true)
% Resets view to be original full image if a crop was set and
% data is available
if obj.dataloaded
obj.Read
end
end
function SetSource(obj, choice)
% obj.SETSOURCE(choice)
% obj.SETSOURCE
%
% SETSOURCE will allow the user to set a desired data source.
% The source can be a folder, a file or multiple files, a
% webcam, an image acquisition device like an sCMOS, or a "live
% data" folder which is monitored for new files. This latter
% option works to load in the latest file saved to a folder as
% the assumption is that the user might be actively acquiring
% new data and saving to the same folder.
%
% INPUTS:
% choice (optional: source name) the data source choice can be
% specified. If the choice does not exist, a warning will be
% given with available options to try.
% Intended datatypes:
%
% OUTPUTS:
% None. This will only set the source but not actually capture
% the data or load data until the user calls the read function.
% Scan for available data sources - at least 3 are always
% available in the full list: File, Folder, Live
List = obj.Datasources; % struct output
fulllist = List.fullList; % full list of all options
imaqobjs = List.imaqobjs; % image acquisition objects/devices only
if nargin < 2 || isempty(choice)
% Ask user to select source
[idx, selectionmade] = listdlg('ListString', fulllist,...
'SelectionMode', 'single',...
'Name', 'Select Image Source',...
'ListSize', [260 80]);
if ~selectionmade
return
end
choice = fulllist{idx};
else
% Checks to see that user selected a valid input option
selectionmade = strcmp(fulllist, choice);
if ~selectionmade
% Adding line break to list to make list of options
fulllist = cellfun(@(x) ['- ' x newline], fulllist, 'UniformOutput', false);
% Warning message regarding invalid selection
wmsg = ['Input choice not valid. Source does not exist.' newline...
'Please choose one of the following: ' newline ...
fulllist{:}];
warning(wmsg)
return
end
end
% Indices will always get reset to 1 but crop coordinates will
% only need to be reset when the user has other data already
% loaded in since new data will have different dimension sizes
obj.ResetIndices
switch choice
case 'Webcam/USB Device'
% Webcam takes snapshots when read is called
% User is prompted to select the webcam from a list
obj.SetupWebcamSource
case 'Folder'
% Use prompted to select folder of files w/ same format
obj.SetupMultiFileSource
case 'File'
% Single file or multiple files read in sequentially
obj.SetupFileSource
case {imaqobjs.name}
% Image acquisition device (webcam, sCMOS, etc.)
% Finds the choice made in the imaq list to pass proper
% device name and device ID to the videoinput class
idx = contains({imaqobjs.name}, choice);
obj.Source = videoinput(imaqobjs(idx).devName, imaqobjs(idx).id);
case 'Live'
% Live folder w refresh whenever read function called
obj.SetupLive(obj.filefolder);
end
% Will first initialize the crops
% First image is loaded up upon setting up the source
obj.Read
end
function SetCropCoords(obj, coords)
% obj.SETCROPCOORDS(coords)
%
% SUMMARY:
% SETCROPCOORDS will set coordinates from a 2D ROI rectangle as
% the region to grab image data from. Takes 2x2 matrix and set
% the first column as the x coordinates and the second column
% as the y coordinates.
%
% INPUTS:
% coords (required: coordinate) a 2x2 matrix where the first
% column is the x coordinate and the second column is the y
% coordinates. The first row is the lower bound of the ROI and
% the second row is the upper bound of the ROI.
% Intended Datatype: uint8, uint16, single, double
%
% OUTPUTS:
% None. The ImageSlice property of the class is updated to have
% been loaded from the specified ROI from the original image
% file.
% Bound Check on the crop coordinates
coords = double(coords);
coords(1,:) = max(coords(1,:), [1 1]);
coords(2,:) = min(coords(2,:), [obj.ncols obj.mrows]);
obj.cropcols = coords(:,1)';
obj.croprows = coords(:,2)';
% Updates image slice to have the adjusted crop
obj.Read
end
function ResetCropCoords(obj)
% obj.RESETCROPCOORDS
%
% SUMMARY:
% RESETCROPCOORDS will reset crop coordinates to then change
% the ROI that is loaded to encompass the full 2D bounds of an
% image.
% Resets to default coordinates
if ~isempty(obj.mrows)
obj.croprows = [1 obj.mrows];
obj.cropcols = [1 obj.ncols];
end
end
function SetLazyLoading(obj, flag)
% obj.SETLAZYLOADING(flag)
% SUMMARY:
% SETLAZYLOADING toggles lazy loading per a logical flag.
%
% INPUTS:
% flag (required: state flag) true will toggle lazy loading on
% and false will disable lazy loading.
% Intended Datatype: logical
%
% OUTPUTS:
% None. Will change image loading behavior.
obj.lazyloading = flag;
end
%% Source Setup Functions
function SetupWebcamSource(obj)
% SETUPWEBCAMSOURCE will check to see which webcam objects are
% available
% Sets up webcam as image server object
wcl = webcamlist;
[idx, flag] = listdlg('ListString', wcl,...
'SelectionMode', 'single',...
'Name', 'Select webcam',...
'ListSize', [260 80]);
if flag
obj.Source = webcam(wcl{idx});
else
return
end
end
function SetupMultiFileSource(obj, f)
% SETUPMULTIFILESOURCE will prompt user to select a folder to
% load files from or take input. If the user has passed in a
% cell array of filepaths, they can be accessed sequentially.
% Creates image data store based off of a folder or cell array
% of files
% User selects folder
if nargin < 2 || isempty(f)
f = mfilename('fullpath');
cpath = fileparts(f);
f = uigetdir(cpath, 'Select source folder');
end
% Sets up an imagedatastore (imds) to load in files
if ischar(f) || isstring(f) || iscell(f)
obj.Refresh2D
obj.Source = imageDatastore(f, 'ReadFcn', @obj.ReadFromMultipleFiles);
obj.numfiles = numel(obj.Source.Files);
obj.fidx = 1; % init file index
obj.Read
else
return
end
end
function SetupFileSource(obj, fpath)
% SETUPFILESOURCE will launch a user interface window to ask
% the user to select file(s) to load in. If a filepath is given,
% this is where the function will start searching, otherwise,
% it looks at the parent working directory or the last folder
% used to load up images.
if nargin < 2 && isempty(obj.filefolder)
fpath = pwd;
elseif nargin < 2 && ~isempty(obj.filefolder)
fpath = obj.filefolder;
end
[file, folder] = uigetfile(obj.filefilt, 'Select image data', fpath, 'MultiSelect','on');
% If a GUI window is open, it will be brought to the front
% again since the prompt may have launched it back
obj.GUIFocus
% file = 0 when user exits, hence a numeric check
if isnumeric(file)
% No file loads
return
else
obj.newstackreq = true;
end
if ischar(file)
% Ensures 2D size data is reset
obj.Refresh2D
% Single file selection
fpath = fullfile(folder, file);
obj.LoadFromString(fpath)
elseif iscell(file)
% Multi file selection - expects same format
files = cellfun(@(x) fullfile(folder, x), file, 'UniformOutput', false);
obj.SetupMultiFileSource(files)
end
end
function Refresh2D(obj)
% REFRESH2D clears 2D information which forces the class to
% then get size information as a result of new data being
% loaded in.
% Resets the indices upon a successful selection
obj.ResetIndices
% Clears ROI information to enable a fresh load
obj.mrows = [];
obj.ncols = [];
end
function SetupLive(obj, f, fext)
% SETUPLIVE will prompt the user to select a folder and file
% format to be observed live. Whenever the read function is
% called, this observed folder will be scanned for any new
% files of the desired file format.
% Sets folder to be observed
if nargin < 2 || isempty(f)
f = mfilename('fullpath');
cpath = fileparts(f);
f = uigetdir(cpath, 'Select source folder');
end
if isnumeric(f)
% Returns if user exits out of the folder selection window
return
else
% Otherwise, source folder is updated
obj.filefolder = f;
end
% Asks user for file extension with default of '.tif'
answer = inputdlg('File extension', 'Set file type', [1 40], {'.tif'});
% Returns if user exits out of the file format selection
if isempty(answer)
return
end
% Sets the extension to be observed
if nargin < 3 || isempty(fext)
% parse answer cell array for requested file extension
fext = answer{:};
% add period in file extension if not already included
if ~strcmp(fext(1), '.')
fext = ['.' fext];
end
end
% Setting the desired file extension
obj.fileext = fext;
% Enables the live loading
obj.LoadLive
end
%% Read and Checks
function Read(obj, d3idx, d4idx, d5idx)
% obj.READ(d3idx, d4idx, d5idx)
% obj.READ(d3idx, [], d5idx)
% obj.READ([], d4idx, d5idx)
% obj.READ(d3idx, d4idx)
% obj.READ([], d4idx)
% obj.READ(d3idx)
% obj.READ
%
% SUMMARY:
% READ will read in a 2D image for the specified indices of the
% third and fourth dimensions of data when the data source is a
% file, collection of files, folder, or multidimensional array.
% If the data source is instead an image acquisition device or
% webcam, a snapshot is instead taken. If the data source is a
% "live data" source type, it will grab the next latest file
% from a folder that it is actively monitoring.
%
% INPUTS:
% d3idx (optional: z slice index) specifies which z slice to grab
% from a volume, if applicable.
% Intended Datatype: uint8, uint16, single, double
%
% d4idx (optional: 4th dimension index) specifies which timepoint,
% stack file, or 4th dimension to grab, if applicable.
% Intended Datatype: uint8, uint16, single, double
%
% OUTPUTS:
% None. Will update the ImageStack and ImageSlice properties of
% the class.
if nargin < 4 || isempty(d5idx)
% Current channel index preserved when not requested
d5idx = obj.channel;
end
if nargin < 3 || isempty(d4idx)
% Current stack / file index preserved when not requested
d4idx = obj.dim4idx;
end
if nargin < 2 || isempty(d3idx)
% Current slice index preserved when not requested
d3idx = obj.slice;
end
% If there is no data source, the function exits since there is
% no data to index
if isempty(obj.Source)
return
end
% Bound checks requested indices and determines which ones
% changed
d3idx = obj.CheckD3Bounds(d3idx);
d4idx = obj.CheckD4Bounds(d4idx);
d5idx = obj.CheckD5Bounds(d5idx);
idx = [d3idx d4idx d5idx];
% Checks if hyper stack dimensions changed
idxchanged = obj.CompareIndices(idx);
obj.newstackreq = any(idxchanged(2:3));
obj.SetD3Index(d3idx)
obj.SetD4Index(d4idx)
obj.SetD5Index(d5idx)
switch class(obj.Source)
case 'matlab.io.datastore.ImageDatastore'
% folder of image files
obj.Source.readimage(obj.fidx);
case 'webcam'
% webcam object source
obj.ReadFromWebcam
case {'uint8', 'uint16', 'single', 'double'}
% image array from workspace
obj.ReadFromArray
case {'string', 'char'}
% single file
obj.LoadFromString
case 'struct'
% live data - always just grabs latest file from folder
obj.LoadLive
case 'matlab.io.MatFile'
% .mat file source
obj.ReadFromMData
case 'VideoReader'
% Video file source
obj.ReadFromVideoFile
case 'videoinput'
% Image acquisition device source
obj.ReadFromImAq
case 'loci.formats.ChannelSeparator'
% Bioformats reader object
obj.ReadFromBF
end
end
function answer = SetIndicesPrompt(obj)
% SETINDICESPROMPT will ask the user to input index values
% for the third and fourth dimensions of their data if those
% dimensions are non-singleton and then update the
% corresponding values.
prompts = {};
def_inpts = {};
if obj.numslices > 1
prompts{end+1} = 'Slice:';
def_inpts{end+1} = num2str(obj.slice);
sflag = true;
else
sflag = false;
end
if obj.dim4 > 1
prompts{end+1} = 'Stack/Timepoint:';
def_inpts{end+1} = num2str(obj.dim4idx);
tflag = true;
else
tflag = false;
end
% Will ask user to navigate when higher dimensions are > 1
if tflag || sflag
t_msg = 'Slice/Stack navigation';
answers = myInputDlg(prompts, t_msg, [], def_inpts);
if ~isempty(answers)
if sflag && tflag
d3idx = str2double(answers{1});
d4idx = str2double(answers{2});
elseif sflag && ~tflag
d3idx = str2double(answers{1});
d4idx = 1;
elseif ~sflag && tflag
d3idx = 1;
d4idx = str2double(answers{1});
end
answer = [d3idx d4idx];
else
answer = [];
end
end
end
end
methods (Access = private)
%% Post Source Set Functions
function SetSize(obj, sz)
% SETSIZE will initialize all dimensions as singletons and then
% assign the data's dimension sizes to non-singleton dimensions
% of the actual data. This assignment is always done in the
% order of YXZTC (3 spatial dimensions, time, and channel).
% Inits dims sets the non-singleton dims
nd = length(sz);
dims = ones(1, 5);
dims(1:nd) = sz;
% Updates class dimension properties
obj.mrows = dims(1);
obj.ncols = dims(2);
obj.numslices = dims(3);
obj.numframes = dims(4);
obj.channels = dims(5);
end
function [idx, jdx] = GetCropIndices(obj)
% CROPINDICES checks to see if a crop ROI has been set and then
% returns the appropriate indices to use.
% Indices in case of ROI
if ~isempty(obj.croprows)
idx = obj.croprows(1):obj.croprows(2);
jdx = obj.cropcols(1):obj.cropcols(2);
else
idx = ':';
jdx = ':';
end
end
function D3 = CheckD3Bounds(obj, z)
% CHECKZBOUNDS will check the bounds on the z dimension of data
% before setting the requested z index.
z = min(obj.numslices, z);
z = max(z, 1);
D3 = z;
end
function D4 = CheckD4Bounds(obj, D4)
% CHECKD4BOUNDS will check the bounds on either the number of
% timepoints in an array/matfile or number of files available
% in a datastore.
D4 = min(obj.dim4, D4);
D4 = max(1, D4);
end
function D5 = CheckD5Bounds(obj, D5)
% CHECKD4BOUNDS will check bounds on number of channels
% available.
D5 = min(obj.channels, D5);
D5 = max(1, D5);
end
function SetD3Index(obj, z)
% SETD3INDEX will set the third dimensions index after bounds
% have been checked. This index represents the position along
% the z axis in a stack if a stack exists.
if isempty(z)
z = 1;
end
obj.slice = z;
end
function SetD4Index(obj, D4)
% SETD4INDEX will set the fourth dimension index to either the
% current timepoint index or the current file index, depending
% on which there are more of per the data source type.
if isempty(D4)
D4 = 1;
end
obj.dim4idx = D4;
% Assigns the fourth dim index to appropriate property
if isempty(obj.numfiles) || obj.numfiles == 1
obj.framenum = D4;
elseif isempty(obj.numframes) || obj.numframes == 1
obj.fidx = D4;
end
end
function SetD5Index(obj, D5)
% SETD5INDEX will set the fifth dimension index set the current
% channel
if isempty(D5)
D5 = 1;
end
obj.channel = D5;
end
function CheckType(obj)
% CHECKTYPE will convert logical to uint8 to prevent algorithms
% from erroring.
if islogical(obj.Slice)
obj.Slice = uint8(obj.Slice);
end
end
function CheckDims(obj)
% CHECKDIMS will ensure that indexed data has no singleton
% dimensions.
sz = size(obj.Slice);
if any(sz==1)
obj.Slice = squeeze(obj.Slice);
end
end
%% Data Loading
% Functions for data loading will accept a single input. The input will
% either be a string or array. This "loads" the data source for the
% first time
function I = LoadFromString(obj, s)
% LOADFROMSTRING will take a string/character array argument to
% load in a 2D image or 3D stack. Alternatively, if the path is
% to a folder, an image data store will be created so that the
% user can navigate across files.
% If no argument is passed, it assumes the same file as before
% is being utilized - assumption is that a different region has
% been specified prior to calling this function
if nargin < 2
s = [obj.filefolder filesep obj.filename obj.fileext];
elseif (~isa(obj.Source, 'matlab.io.datastore.ImageDatastore') && obj.fidx ~= 1) || ~obj.dataloaded
% Memory check with 500 MB threshold allowed
good2load = obj.MemoryCheck(s, 5e8, obj.lazyloading);
if ~good2load
return
end
end
% Getting number of output arguments
nout = nargout;
% Checks if string is folder or file
str_type = exist(s, 'file');
if str_type == 7
% Folder/multiple files converted to image datastore -
% first image is immediately loaded by
obj.Source = imageDatastore(s, 'ReadFcn', @obj.ReadFromMultipleFiles);
obj.numfiles = numel(obj.Source.Files);
obj.fidx = 1;
% Reads in the first image
obj.Read
return
elseif str_type == 2
% String is to a file that exists, function continues
else
% String identifies neither a file nor a folder, function
% will exit
return
end
% Check if this is a new file being loaded from a different
% place
[newfpath, ~, fext] = fileparts(s);
newfile = isempty(obj.mrows) ||...
isempty(obj.fileext) ||...
~strcmp(newfpath, obj.filefolder) ||...
~strcmp(fext, obj.fileext);
% Save file selection info
[obj.filefolder, obj.filename, obj.fileext] = fileparts(s);
switch obj.fileext
case '.mat'
% M-data (matfile) source with variable/array
if newfile
obj.LoadFromMData(s)
else
obj.ReadFromMData
end
case {'.tif', '.tiff'}
% Tiff image file sources
if newfile
obj.LoadFromTiff(s)
else
obj.ReadFromTiff
end
% Prevents source overwrite if called from imds source
obj.Check4IMDS(nout)
case {'.png', '.jpg', '.jpeg', '.jfif'}
% Non-tiff image file sources
if newfile
obj.LoadFromImageFile(s)
else
obj.ReadFromImageFile
end
% Prevents source overwrite if called from imds source
obj.Check4IMDS(nout)
case {'.avi', '.mp4', '.mpg', '.mpeg'}
% Video setup as a videoreader object
if newfile
obj.LoadFromVideoFile(s)
else
obj.ReadFromVideoFile
end
case obj.bffileexts
% Does nothing if user cannot use BF
if isempty(obj.bffileexts)
warning(['User does not have BioFormats. ' ...
'No data loaded'])
return
end
% bioformats compatible file extensions
if newfile
obj.LoadFromBF(s)
else
obj.ReadFromBF
end
end
% Ensures image output when class method is called from
% imds source - when mult. files loaded up
if nout == 1
I = obj.Slice;
end
end
function LoadFromMData(obj, s)
% matfile object use reduces memory usage
mfobj = matfile(s);
vars = fieldnames(mfobj);
idx = ~strcmp(vars, 'Properties');
vars = vars(idx);
numvars = numel(vars);
% .mat file data to be loaded - user selects variable
if numvars > 1
[idx, tf] = listdlg('ListString', vars);
% user exits variable selection
if ~tf
return
end
% verifying response
vname = vars{idx};
else
vname = vars{1};
end
% Saves variable name for future access from matfile
obj.variable = vname;
% Check that variable is valid array data
fileinfo = whos(mfobj, obj.variable);
isArr = strcmp(fileinfo.class, {'uint8', 'uint16', 'uint32', 'single', 'double'});
if any(isArr)
% Source settings and dimension information
obj.Source = mfobj;
obj.SetSize(fileinfo.size)
% Ensures the full 2D slice is loaded upon initial load
obj.ResetCropCoords
% Reading in the MData variable
obj.ReadFromMData
else
% Errors when user select variable that is not a numerical
% array
emsg = 'Selected variable is not a numerical array';
error(emsg)
end
end