-
Notifications
You must be signed in to change notification settings - Fork 20
/
TIFFStack.m
executable file
·1891 lines (1554 loc) · 70.9 KB
/
TIFFStack.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
% <strong>TIFFStack</strong> - Manipulate a TIFF file like a tensor
%
% Usage: tsStack = <<strong>TIFFStack</strong>(strFilename <, bInvert, vnInterleavedFrameDims>)
%
% A TIFFStack object behaves like a read-only memory mapped TIFF file. The
% entire image stack is treated as a matlab tensor. Each frame of the file must
% have the same dimensions. Reading the image data is optimised to the extent
% possible; the header information is only read once.
%
% If this software is useful to your academic work, please cite our
% publication in lieu of thanks:
%
% D R Muir and B M Kampa, 2015. "FocusStack and StimServer: a new open
% source MATLAB toolchain for visual stimulation and analysis of two-photon
% calcium neuronal imaging data". Frontiers in Neuroinformatics 8 (85).
% DOI: <a href="http://dx.doi.org/10.3389/fninf.2014.00085">10.3389/fninf.2014.00085</a>
%
% This class attempts to use the version of tifflib built-in to recent
% versions of Matlab, if available. Otherwise this class uses a modified
% version of tiffread [2, 3] to read data.
%
% permute, ipermute and transpose are now transparantly supported. Note
% that to read a pixel, the entire frame containing that pixel is read. So
% reading a Z-slice of the stack will read in the entire stack.
%
% Some TIFF file writing software introduces custom or poorly-formed tags.
% This causes tifflib to produce lots of warnings. These warnings can be
% ignored by setting:
%
% >> w = warning('off', 'MATLAB:imagesci:tiffmexutils:libtiffWarning');
% >> warning('off', 'MATLAB:imagesci:tifftagsread:expectedTagDataFormat');
%
% and later restored with:
%
% >> warning(w);
%
% -------------------------------------------------------------------------
%
% <strong>Construction</strong>
% >> tsStack = TIFFStack('test.tiff'); % Construct a TIFF stack associated with a file
%
% >> tsStack = TIFFStack('test.tiff', true); % Indicate that the image data should be inverted
%
% tsStack =
%
% TIFFStack handle
%
% Properties:
% bInvert: 0
% strFilename: [1x9 char]
% sImageInfo: [5x1 struct]
% strDataClass: 'uint16'
%
% Usage:
%
% >> tsStack(:, :, 3); % Retrieve the 3rd frame of the stack, all planes
%
% >> tsStack(:, :, 1, 3); % Retrieve the 3rd plane of the 1st frame
%
% >> size(tsStack) % Find the size of the stack (rows, cols, frames, planes per pixel)
%
% ans =
%
% 128 128 5 1
%
% >> tsStack(4); % Linear indexing is supported
%
% >> tsStack.bInvert = true; % Turn on data inversion
%
% >> getFilename(tsStack) % Retrieve the 'strFilename' property
% >> getInvert(tsStack) % Retrive the 'bInvert' property
% >> getImageInfo(tsStack) % Retrieve the 'sImageInfo' property
% >> getDataClass(tsStack) % Retrive the 'strDataClass' property
%
% -------------------------------------------------------------------------
%
% <strong>De-interleaving frame dimensions in complex stacks</strong>
% Some TIFF generation software stores multiple samples per pixel as
% interleaved frames in a TIFF file. Other complex stacks may include
% multiple different images per frame of time (e.g. multiple cameras or
% different imaged locations per frame). TIFFStack allows these files to be
% de-interleaved, such that each conceptual data dimension has its own
% referencing dimension within matlab.
%
% This functionality uses the optional 'vnInterleavedFrameDims' argument.
% This is a vector of dimensions that were interleaved into the single
% frame dimension in the stack.
%
% For example, a stack contains 2 channels of data per pixel, and 3 imaged
% locations per frame, all interleaved into the TIFF frame dimension. The
% stack contains 10 conceptual frames, and each frame contains 5x5 pixels.
%
% The stack is therefore conceptually of dimensions [5 5 2 3 10 1], but
% appears on disk with dimensions [5 5 60 1]. (The final dimension
% corresponds to the samples-per-pixel dimension of the TIFF file).
%
% >> tsStack = TIFFStack('file.tif', [], [2 3 10]);
% >> size(tsStack)
%
% ans =
%
% 5 5 2 3 10
%
% Permutation and indexing now works seamlessly on this stack, with each
% conceptual dimension de-interleaved.
%
% If desired, the final number of frames can be left off
% 'vnInterleavedFrameDims'; for example:
%
% >> tsStack = TIFFStack('file.tif', [], [2 3]);
% >> size(tsStack)
%
% ans =
%
% 5 5 2 3 10
%
% Note: You must be careful that you specify the dimensions in the
% appropriate order, as interleaved in the stack. Also, if the stack
% contains multiple samples per pixel in native TIFF format, the
% samples-per-pixel dimension will always be pushed to the final dimension.
%
% -------------------------------------------------------------------------
%
% <strong>ImageJ stacks</strong>
% ImageJ HyperStacks are automatically deinterleaved, if encountered. By
% default, the stacks will be presented as [Y X T Z C]. They can of course
% be permuted. If desired, the interleaving can be overridden by providing
% an explicit 'vnInterleavedFrameDims'.
%
% ImageJ writes "fake" big stacks as raw binary data, with a TIF file shim
% as a header. These appear to Matlab as a TIF file containing a single
% frame. TIFFStack loads these files using MappedTensor, when available. If
% MappedTensor is not available, a warning will be issued.
%
% References:
% [1] D R Muir and B M Kampa, 2015. "FocusStack and StimServer: a new open
% source MATLAB toolchain for visual stimulation and analysis of two-photon
% calcium neuronal imaging data". Frontiers in Neuroinformatics 8 (85).
% DOI: <a href="http://dx.doi.org/10.3389/fninf.2014.00085">10.3389/fninf.2014.00085</a>
%
% [2] Francois Nedelec, Thomas Surrey and A.C. Maggs. Physical Review Letters
% 86: 3192-3195; 2001. DOI: <a href="http://dx.doi.org/10.1103/PhysRevLett.86.3192">10.1103/PhysRevLett.86.3192</a>
%
% [3] <a href="http://www.cytosim.org">http://www.cytosim.org</a>
% Author: Dylan Muir <muir@hifo.uzh.ch>
% Created: 28th June, 2011
%% Class definition
classdef TIFFStack < handle
properties
bInvert; % - A boolean flag that determines whether or not the image data will be inverted
end
properties (SetAccess = private)
strFilename = []; % - The name of the TIFF file on disk
sImageInfo; % - The TIFF header information
strDataClass; % - The matlab class in which data will be returned
end
properties (SetAccess = private, GetAccess = private)
bForceTiffread % - Force the use of tiffread, rather than trying to use TiffLib
vnDataSize; % - Cached size of the TIFF stack
vnApparentSize; % - Apparent size of the TIFF stack
TIF; % \
TIF_tr31; % |- Cached header info for tiffread31 speedups
HEADER; % /
bUseTiffLib; % - Flag indicating whether TiffLib is being used
bMTStack; % - Flag indicating MappedTensor is being used
fhReadFun; % - When using Tiff class, function for reading data
fhSetDirFun; % - When using Tiff class, function for setting the directory
vnDimensionOrder; % - Internal dimensions order to support permutation
fhRepSum; % - Function handle to (hopefully) accellerated repsum function
fhCastFun; % - The matlab function that casts data to the required return class
end
methods
% TIFFStack - CONSTRUCTOR
function oStack = TIFFStack(strFilename, bInvert, vnInterleavedFrameDims, bForceTiffread)
% - Check usage
if (~exist('strFilename', 'var') || ~ischar(strFilename))
help TIFFStack;
error('TIFFStack:Usage', ...
'*** TIFFStack: Incorrect usage.');
end
% - Should we force TIFFStack to use tiffread, rather than libTiff?
if (~exist('bForceTiffread', 'var') || isempty(bForceTiffread))
bForceTiffread = false;
end
oStack.bForceTiffread = bForceTiffread;
% - Can we use the accelerated TIFF library?
if (exist('tifflib') ~= 3) %#ok<EXIST>
% - Try to copy the library
strTiffLibLoc = which('/private/tifflib');
strTIFFStackLoc = fileparts(which('TIFFStack'));
copyfile(strTiffLibLoc, fullfile(strTIFFStackLoc, 'private'), 'f');
end
oStack.bUseTiffLib = (exist('tifflib') == 3) & ~bForceTiffread; %#ok<EXIST>
if (~oStack.bUseTiffLib)
warning('TIFFStack:SlowAccess', ...
'--- TIFFStack: Using slower non-TiffLib access.');
end
% - Get accelerated repsum function, if possible
oStack.fhRepSum = GetMexFunctionHandles;
% - Check for inversion flag
if (~exist('bInvert', 'var') || isempty(bInvert))
bInvert = false;
end
oStack.bInvert = bInvert;
% - Check for frame dimensions
if (~exist('vnInterleavedFrameDims', 'var'))
vnInterleavedFrameDims = [];
else
validateattributes(vnInterleavedFrameDims, {'single', 'double'}, {'integer', 'real', 'positive'}, ...
'TIFFStack', 'vnInterleavedFrameDims');
end
% - See if filename exists
if (~exist(strFilename, 'file'))
error('TIFFStack:InvalidFile', ...
'*** TIFFStack: File [%s] does not exist.', strFilename);
end
% - Assign absolute file path to stack
strFilename = get_full_file_path(strFilename);
oStack.strFilename = strFilename;
% - Get image information
try
% - Read and store image information (using tiffread for speed and compatibility)
[oStack.TIF, oStack.HEADER, sInfo] = tiffread31_header(strFilename);
oStack.TIF_tr31 = oStack.TIF;
% - Detect a ImageJ fake BigTIFF stack
[bIsImageJBigStack, bIsImageJHyperStack, vnStackDims, vnInterleavedIJFrameDims] = IsImageJBigStack(tiffread31_readtags(oStack.TIF_tr31, oStack.HEADER, 1), numel(oStack.HEADER));
% - Handle ImageJ big stacks with MappedTensor
if (bIsImageJBigStack)
[oStack.TIF, oStack.bMTStack, oStack.strDataClass] = OpenImageJBigStack(oStack, vnStackDims);
% - Could we use a MappedTensor?
if (~oStack.bMTStack)
% - No, so just access the first frame
bIsImageJBigStack = false; %#ok<NASGU>
bIsImageJHyperStack = false;
warning('TIFFStack:ImageJBigStackUnsupported', ...
'--- TIFFStack: Warning: This is an ImageJ "fake" TIF file. MappedTensor must be available to read this file.');
end
end
% - Detect a very long stack
if ((numel(sInfo) > 2^16) && oStack.bUseTiffLib)
warning('TIFFStack:LongStack', ...
'--- TIFFSTack: Warning: This stack has more than 2^16 frames, so Matlab/tifflib cannot read it natively.\n Using slower non-Tifflib access.');
oStack.bUseTiffLib = false;
end
% - Deinterleave hyperstacks automatically
bImageJDeinterleaving = bIsImageJHyperStack && isempty(vnInterleavedFrameDims);
if bImageJDeinterleaving
vnInterleavedFrameDims = vnInterleavedIJFrameDims;
end
% - Initialise object, depending on underlying access method
if (oStack.bMTStack)
% - Fix up stack size
sInfo = repmat(sInfo(1), vnStackDims(3), 1);
elseif (oStack.bUseTiffLib)
% - Create a Tiff object
oStack.TIF = tifflib('open', strFilename, 'r');
% - Check data format
if(TiffgetTag(oStack.TIF, 'Photometric') == Tiff.Photometric.YCbCr)
error('TIFFStack:UnsupportedFormat', ...
'*** TIFFStack: YCbCr images are not supported.');
end
% - Use Tiff to get the data class for this tiff
nDataClass = TiffgetTag(oStack.TIF, 'SampleFormat');
switch (nDataClass)
case Tiff.SampleFormat.UInt
switch (sInfo(1).BitsPerSample(1))
case 1
oStack.strDataClass = 'logical';
case 8
oStack.strDataClass = 'uint8';
case 16
oStack.strDataClass = 'uint16';
case 32
oStack.strDataClass = 'uint32';
case 64
oStack.strDataClass = 'uint64';
otherwise
error('TIFFStack:UnsupportedFormat', ...
'*** TIFFStack: The sample format of this TIFF stack is not supported.');
end
case Tiff.SampleFormat.Int
switch (sInfo(1).BitsPerSample(1))
case 1
oStack.strDataClass = 'logical';
case 8
oStack.strDataClass = 'int8';
case 16
oStack.strDataClass = 'int16';
case 32
oStack.strDataClass = 'int32';
case 64
oStack.strDataClass = 'int64';
otherwise
error('TIFFStack:UnsupportedFormat', ...
'*** TIFFStack: The sample format of this TIFF stack is not supported.');
end
case Tiff.SampleFormat.IEEEFP
switch (sInfo(1).BitsPerSample(1))
case {1, 8, 16, 32}
oStack.strDataClass = 'single';
case 64
oStack.strDataClass = 'double';
otherwise
error('TIFFStack:UnsupportedFormat', ...
'*** TIFFStack: The sample format of this TIFF stack is not supported.');
end
otherwise
error('TIFFStack:UnsupportedFormat', ...
'*** TIFFStack: The sample format of this TIFF stack is not supported.');
end
% -- Assign accelerated reading function
strReadFun = 'TS_read_Tiff';
% - Tiled or striped
if (tifflib('isTiled', oStack.TIF))
strReadFun = [strReadFun '_tiled'];
else
strReadFun = [strReadFun '_striped'];
end
% - Chunky or planar
if (isequal(TiffgetTag(oStack.TIF, 'PlanarConfiguration'), Tiff.PlanarConfiguration.Chunky))
strReadFun = [strReadFun '_chunky'];
elseif (isequal(TiffgetTag(oStack.TIF, 'PlanarConfiguration'), Tiff.PlanarConfiguration.Separate))
strReadFun = [strReadFun '_planar'];
else
error('TIFFStack:UnsupportedFormat', ...
'*** TIFFStack: The planar configuration of this TIFF stack is not supported.');
end
strSetDirFun = 'TS_set_directory';
% - Check for zero-based referencing
try
tifflib('computeStrip', oStack.TIF, 0);
catch
strReadFun = [strReadFun '_pre2014'];
strSetDirFun = [strSetDirFun '_pre2014'];
end
% - Convert into function handles
oStack.fhReadFun = str2func(strReadFun);
oStack.fhSetDirFun = str2func(strSetDirFun);
% - Fix up rows per strip (inconsistency between Windows and
% OS X Tifflib
nRowsPerStrip = TiffgetTag(oStack.TIF, 'RowsPerStrip');
if ~isfield(sInfo, 'RowsPerStrip') || (nRowsPerStrip ~= sInfo(1).RowsPerStrip)
[sInfo.RowsPerStrip] = deal(nRowsPerStrip);
end
% - Attempt to read tile width and length
try
[sInfo.TileWidth] = deal(TiffgetTag(oStack.TIF, 'TileWidth'));
catch
[sInfo.TileWidth] = deal(1);
end
try
[sInfo.TileLength] = deal(TiffgetTag(oStack.TIF, 'TileLength'));
catch
[sInfo.TileLength] = deal(1);
end
% - Read max and min sample values
[sInfo.MaxSampleValue] = deal(TiffgetTag(oStack.TIF, 'MaxSampleValue'));
[sInfo.MinSampleValue] = deal(TiffgetTag(oStack.TIF, 'MinSampleValue'));
else
% - Read TIFF header for tiffread31
% [oStack.TIF, oStack.HEADER] = tiffread31_header(strFilename);
oStack.TIF.file = fopen(strFilename, 'r', 'l');
% - Use tiffread31 to get the data class for this tiff
fPixel = tiffread31_readimage(oStack.TIF, oStack.HEADER, 1);
fPixel = fPixel(1, 1, :);
oStack.strDataClass = class(fPixel);
end
% - Use imread to get the data class for this tiff
% fPixel = imread(strFilename, 'TIFF', 1, 'PixelRegion', {[1 1], [1 1]});
% oStack.strDataClass = class(fPixel);
% -- Assign casting function
oStack.fhCastFun = str2func(oStack.strDataClass);
% - Record stack size
if (oStack.bMTStack)
oStack.vnDataSize = vnStackDims;
oStack.vnApparentSize = oStack.vnDataSize;
% - Initialise dimension order
oStack.vnDimensionOrder = 1:numel(oStack.vnApparentSize);
% - Permute first two dimensions
oStack = permute(oStack, [2 1 3:numel(vnStackDims)]);
else
oStack.vnDataSize = [sInfo(1).Height sInfo(1).Width numel(sInfo) sInfo(1).SamplesPerPixel];
% - Initialise dimension order
oStack.vnDimensionOrder = 1:numel(oStack.vnDataSize);
end
% - Initialize apparent stack size, de-interleaving along the frame dimension
if isempty(vnInterleavedFrameDims)
% - No de-interleaving
oStack.vnApparentSize = oStack.vnDataSize;
elseif (prod(vnInterleavedFrameDims) ~= oStack.vnDataSize(3))
% - Be lenient by allowing frames dimension to be left out of arguments
if (mod(oStack.vnDataSize(3), prod(vnInterleavedFrameDims)) == 0)
% - Work out number of apparent frames
nNumApparentFrames = oStack.vnDataSize(3) ./ prod(vnInterleavedFrameDims);
oStack.vnApparentSize = [oStack.vnDataSize(1:2) vnInterleavedFrameDims(:)' nNumApparentFrames oStack.vnDataSize(4)];
oStack.vnDimensionOrder = 1:numel(oStack.vnApparentSize);
else
% - Incorrect total number of deinterleaved frames
error('TIFFStack:WrongFrameDims', ...
'*** TIFFStack: When de-interleaving a stack, the total number of frames must not change.');
end
else
% - Record apparent stack dimensions
oStack.vnApparentSize = [oStack.vnDataSize(1:2) vnInterleavedFrameDims(:)' oStack.vnDataSize(4)];
oStack.vnDimensionOrder = 1:numel(oStack.vnApparentSize);
end
% - Fix up dimensions order for ImageJ HyperStack
if (bImageJDeinterleaving)
oStack = permute(oStack, [1 2 5 4 3]);
end
% - Record image information
oStack.sImageInfo = sInfo;
catch mErr
base_ME = MException('TIFFStack:InvalidFile', ...
'*** TIFFStack: Could not open file [%s].', strFilename);
new_ME = addCause(base_ME, mErr);
throw(new_ME);
end
end
% delete - DESTRUCTOR
function delete(oStack)
if (oStack.bUseTiffLib)
% - Close the TIFF file, if opened by TiffLib
if (~isempty(oStack.TIF))
tifflib('close', oStack.TIF);
end
end
% - Close the TIFF file, if opened by tiffread31_header
if (isfield(oStack.TIF_tr31, 'file') && ~isempty(fopen(oStack.TIF_tr31.file)))
fclose(oStack.TIF_tr31.file);
end
end
% diagnostic - METHOD Display some diagnostics about a stack
function diagnostic(oStack)
disp(oStack);
fprintf('<strong>Private properties:</strong>\n');
fprintf(' vnDataSize: ['); fprintf('%d ', oStack.vnDataSize); fprintf(']\n');
fprintf(' vnApparentSize: ['); fprintf('%d ', oStack.vnApparentSize); fprintf(']\n');
fprintf(' vnDimensionOrder: ['); fprintf('%d ', oStack.vnDimensionOrder); fprintf(']\n');
fprintf(' bUseTiffLib: %d\n', oStack.bUseTiffLib);
fprintf(' bMTStack: %d\n', oStack.bMTStack);
fprintf(' fhReadFun: %s\n', func2str(oStack.fhReadFun));
fprintf(' fhSetDirFun: %s\n', func2str(oStack.fhSetDirFun));
fprintf(' fhRepSum: %s\n', func2str(oStack.fhRepSum));
fprintf(' fhCastFun: %s\n', func2str(oStack.fhCastFun));
end
function [TIF, HEADER] = diagnostic_HEADER(oStack)
TIF = oStack.TIF;
HEADER = oStack.HEADER;
end
%% --- Overloaded subsref
function [varargout] = subsref(oStack, S)
switch S(1).type
case '()'
% - Test for valid subscripts
cellfun(@isvalidsubscript, S.subs);
% - Record stack size
nNumRefDims = numel(S.subs);
vnReferencedTensorSize = size(oStack);
nNumNZStackDims = numel(vnReferencedTensorSize);
nNumTotalStackDims = max(numel(oStack.vnDimensionOrder), nNumNZStackDims);
vnFullTensorSize = vnReferencedTensorSize;
vnFullTensorSize(nNumNZStackDims+1:nNumTotalStackDims) = 1;
vnFullTensorSize(vnFullTensorSize == 0) = 1;
bLinearIndexing = false;
% - Convert logical indexing to indices
for (nDim = 1:numel(S.subs))
if (islogical(S.subs{nDim}))
S.subs{nDim} = find(S.subs{nDim});
end
end
% - Check dimensionality and trailing dimensions
if (nNumRefDims == 1)
% - Catch "read whole stack" case
if (iscolon(S.subs{1}))
S.subs = num2cell(repmat(':', 1, nNumNZStackDims));
vnRetDataSize = [prod(vnReferencedTensorSize), 1];
else
% - Get equivalent subscripted indexes and permute
vnTensorSize = size(oStack);
if any(S.subs{1}(:) > prod(vnTensorSize))
error('TIFFStack:badsubscript', ...
'*** TIFFStack: Index exceeds stack dimensions.');
else
[cIndices{1:nNumTotalStackDims}] = ind2sub(vnTensorSize, S.subs{1});
end
% - Permute dimensions
vnInvOrder(oStack.vnDimensionOrder(1:nNumTotalStackDims)) = 1:nNumTotalStackDims;
S.subs = cIndices(vnInvOrder(vnInvOrder ~= 0));
vnRetDataSize = size(S.subs{1});
bLinearIndexing = true;
end
elseif (nNumRefDims < nNumNZStackDims)
% - Wrap up trailing dimensions, matlab style, using linear indexing
vnReferencedTensorSize(nNumRefDims) = prod(vnReferencedTensorSize(nNumRefDims:end));
vnReferencedTensorSize = vnReferencedTensorSize(1:nNumRefDims);
% - Catch "read whole stack" case
if (all(cellfun(@iscolon, S.subs)))
[S.subs{nNumRefDims+1:nNumTotalStackDims}] = deal(':');
vnRetDataSize = vnReferencedTensorSize;
else
% - Convert to linear indexing
bLinearIndexing = true;
[S.subs{1}, vnRetDataSize] = GetLinearIndicesForRefs(S.subs, vnReferencedTensorSize, oStack.fhRepSum);
S.subs = S.subs(1);
[S.subs{1:nNumTotalStackDims}] = ind2sub(vnFullTensorSize, S.subs{1});
% - Inverse permute index order
vnInvOrder(oStack.vnDimensionOrder(1:nNumTotalStackDims)) = 1:nNumTotalStackDims;
S.subs = S.subs(vnInvOrder(vnInvOrder ~= 0));
end
elseif (nNumRefDims == nNumNZStackDims)
% - Check for colon references
vbIsColon = cellfun(@iscolon, S.subs);
vnRetDataSize = cellfun(@numel, S.subs);
vnRetDataSize(vbIsColon) = vnReferencedTensorSize(vbIsColon);
% - Permute index order
S.subs(nNumNZStackDims+1:nNumTotalStackDims) = {1};
vnInvOrder(oStack.vnDimensionOrder(1:nNumTotalStackDims)) = 1:nNumTotalStackDims;
S.subs = S.subs(vnInvOrder(vnInvOrder ~= 0));
else % (nNumRefDims > nNumNZStackDims)
% - Check for non-colon references
vbIsColon = cellfun(@iscolon, S.subs);
% - Check for non-unitary references
vbIsUnitary = cellfun(@(c)(isequal(c, 1)), S.subs);
% - Check for non-empty references
vbIsEmpty = cellfun(@isempty, S.subs);
% - Check only trailing dimensions
vbTrailing = [false(1, nNumNZStackDims) true(1, nNumRefDims-nNumNZStackDims)];
% - Check trailing dimensions for inappropriate indices
if (any(vbTrailing & (~vbIsColon & ~vbIsUnitary & ~vbIsEmpty)))
% - This is an error
error('TIFFStack:badsubscript', ...
'*** TIFFStack: Index exceeds stack dimensions.');
end
% - Catch empty refs
if (~any(vbIsEmpty))
% - Only keep relevant dimensions
S.subs = S.subs(1:nNumNZStackDims);
end
% - Determine returned data size
vnReferencedTensorSize(nNumNZStackDims+1:nNumRefDims) = 1;
vnReferencedTensorSize(vnReferencedTensorSize == 0) = 1;
vbIsColon = cellfun(@iscolon, S.subs);
vnRetDataSize = cellfun(@numel, S.subs);
vnRetDataSize(vbIsColon) = vnReferencedTensorSize(vbIsColon);
% - Permute index order
S.subs(nNumNZStackDims+1:nNumTotalStackDims) = {1};
vnInvOrder(oStack.vnDimensionOrder(1:nNumTotalStackDims)) = 1:nNumTotalStackDims;
S.subs = S.subs(vnInvOrder(vnInvOrder ~= 0));
end
% - Catch empty refs
if (prod(vnRetDataSize) == 0)
[varargout{1:nargout}] = zeros(vnRetDataSize);
return;
end
% - Re-interleave frame indices for deinterleaved stacks
if (numel(oStack.vnApparentSize) > 4)
% - Record output data size in deinterleaved space
if (~bLinearIndexing)
vnOutputSize = cellfun(@numel, S.subs);
vbIsColon = cellfun(@iscolon, S.subs);
vnOutputSize(vbIsColon) = oStack.vnApparentSize(vbIsColon);
end
% - Get frame
cFrameSubs = S.subs(3:end-1);
if all(cellfun(@iscolon, cFrameSubs))
S.subs = {S.subs{1} S.subs{2} ':' S.subs{end}};
else
if (bLinearIndexing)
vnFrameIndices = sub2ind(oStack.vnApparentSize(3:end-1), cFrameSubs{:});
else
tnFrameIndices = reshape(1:oStack.vnDataSize(3), ...
oStack.vnApparentSize(3:end-1));
vnFrameIndices = tnFrameIndices(cFrameSubs{:});
end
% - Construct referencing subscripts for raw stack
S.subs = [S.subs(1:2) reshape(vnFrameIndices, [], 1) S.subs(end)];
end
end
% - Access stack (MappedTensor or tifflib or tiffread)
if (oStack.bMTStack)
tfData = TS_read_data_MappedTensor(oStack, S.subs, bLinearIndexing);
elseif (oStack.bUseTiffLib)
tfData = TS_read_data_Tiff(oStack, S.subs, bLinearIndexing);
else
tfData = TS_read_data_tiffread(oStack, S.subs, bLinearIndexing);
end
% - Permute dimensions, if linear indexing has not been used
if (~bLinearIndexing)
% - Reshape resulting data in case of deinterleaved stacks
if (numel(oStack.vnApparentSize) > 4)
tfData = reshape(tfData, vnOutputSize);
end
tfData = permute(tfData, oStack.vnDimensionOrder);
end
% - Reshape returned data to concatenate trailing dimensions (just as matlab does)
if (~isequal(size(tfData), vnRetDataSize))
tfData = reshape(tfData, vnRetDataSize);
end
[varargout{1:nargout}] = tfData;
otherwise
error('TIFFStack:InvalidReferencing', ...
'*** TIFFStack: Only ''()'' referencing is supported by TIFFStacks.');
end
end
%% --- Getter methods
function strFilename = getFilename(oStack)
strFilename = oStack.strFilename;
end
function sImageInfo = getImageInfo(oStack)
sImageInfo = oStack.sImageInfo;
end
function vsTags = getImageTags(oStack, vnFrames)
% getImageTags - METHOD Read TIFF tags for individual frames
%
% Usage: vsTags = getImageTags(oStack, vnFrames)
%
% 'oStack' is a TIFFStack object. 'vnFrames' is a vector of frame
% indices into the stack.
%
% 'vsTags' will be a struct array, with each element of the array
% containing all tags for the corresponding frame index in
% 'vnFrames'.
if (nargin < 2)
help TIFFStack/getImageTags;
error('TIFFStack:Usage', 'TIFFStack/getImageTags: ''vnFrames'' is a required argument.');
end
% - Extract tags for these frames
vsTags = tiffread31_readtags(oStack.TIF_tr31, oStack.HEADER, vnFrames);
end
function bInvert = getInvert(oStack)
bInvert = oStack.bInvert;
end
function strDataClass = getDataClass(oStack)
strDataClass = oStack.strDataClass;
end
%% --- Overloaded numel, size, ndims, permute, ipermute, ctranspose, transpose, cat, horzcat, vertcat
function [n] = numel(oStack, varargin)
n = prod(size(oStack)); %#ok<PSIZE>
end
% size - METHOD Overloaded size function
function [varargout] = size(oStack, vnDimensions)
% - Get original tensor size, and extend dimensions if necessary
vnApparentSize = oStack.vnApparentSize; %#ok<PROPLC,PROP>
vnApparentSize(end+1:numel(oStack.vnDimensionOrder)) = 1; %#ok<PROPLC,PROP>
% - Return the size of the tensor data element, permuted
vnSize = vnApparentSize(oStack.vnDimensionOrder); %#ok<PROPLC,PROP>
% - Trim trailing unitary dimensions
vbIsUnitary = vnSize == 1;
if (vbIsUnitary(end))
nLastNonUnitary = find(~vbIsUnitary, 1, 'last');
if (nLastNonUnitary < numel(vnSize))
vnSize = vnSize(1:nLastNonUnitary);
end
end
% - Return specific dimension(s)
if (exist('vnDimensions', 'var'))
if (~isnumeric(vnDimensions) || any(vnDimensions < 1))
error('TIFFStack:DimensionMustBePositiveInteger', ...
'*** TIFFStack: Dimensions argument must be a positive integer.');
end
vbExtraDimensions = vnDimensions > numel(vnSize);
% - Return the specified dimension(s)
vnSizeOut(~vbExtraDimensions) = vnSize(vnDimensions(~vbExtraDimensions));
vnSizeOut(vbExtraDimensions) = 1;
else
vnSizeOut = vnSize;
end
% - Handle differing number of size dimensions and number of output
% arguments
nNumArgout = max(1, nargout);
if (nNumArgout == 1)
% - Single return argument -- return entire size vector
varargout{1} = vnSizeOut;
elseif (nNumArgout <= numel(vnSizeOut))
% - Several return arguments -- return single size vector elements,
% with the remaining elements grouped in the last value
varargout(1:nNumArgout-1) = num2cell(vnSizeOut(1:nNumArgout-1));
varargout{nNumArgout} = prod(vnSizeOut(nNumArgout:end));
else %(nNumArgout > numel(vnSize))
% - Output all size elements
varargout(1:numel(vnSizeOut)) = num2cell(vnSizeOut);
% - Deal out trailing dimensions as '1'
varargout(numel(vnSizeOut)+1:nNumArgout) = {1};
end
end
% ndims - METHOD Overloaded ndims function
function [nNumDims] = ndims(oStack)
nNumDims = numel(size(oStack));
end
% permute - METHOD Overloaded permute function
function [oStack] = permute(oStack, vnNewOrder)
oStack.vnDimensionOrder(1:numel(vnNewOrder)) = oStack.vnDimensionOrder(vnNewOrder);
end
% ipermute - METHOD Overloaded ipermute function
function [oStack] = ipermute(oStack, vnOldOrder)
vnNewOrder(vnOldOrder) = 1:numel(vnOldOrder);
oStack = permute(oStack, vnNewOrder);
end
% ctranspose - METHOD Overloaded ctranspose function
function [oStack] = cstranspose(oStack)
oStack = transpose(oStack);
end
% transpose - METHOD Overloaded transpose function
function [oStack] = transpose(oStack)
oStack = permute(oStack, [2 1]);
end
% cat - METHOD Overloaded cat, horzcat, vertcat functions
function [varargout] = cat(varargin) %#ok<STOUT>
error('TIFFStack:Concatenation', ...
'*** TIFFStack: Concatenation is not supported by TIFFStack.');
end
function [varargout] = horzcat(varargin) %#ok<STOUT>
error('TIFFStack:Concatenation', ...
'*** TIFFStack: Concatenation is not supported by TIFFStack.');
end
function [varargout] = vertcat(varargin) %#ok<STOUT>
error('TIFFStack:Concatenation', ...
'*** TIFFStack: Concatenation is not supported by TIFFStack.');
end
%% --- Overloaded end
function nLength = end(oStack, nEndDim, nTotalRefDims)
vnSizes = size(oStack);
if (nEndDim < nTotalRefDims)
nLength = vnSizes(nEndDim);
else
nLength = prod(vnSizes(nEndDim:end));
end
end
%% --- Overloaded sum, nansum, mean, nanmean
% sum - METHOD Overloaded sum function
function [tfResult, tnNumNonNaNs] = sum(oStack, nDim, flag, bIgnoreNaNs)
% - If this function is called, it must be a sum over the entire stack
if nargin==2 && ischar(nDim)
flag = nDim;
elseif nargin < 3
flag = 'default';
end
if nargin == 1 || (nargin == 2 && ischar(nDim))
nDim = find(size(oStack)~=1,1);
if isempty(nDim), nDim = 1; end
end
if (~exist('bIgnoreNaNs', 'var'))
bIgnoreNaNs = true;
end
% - Set up referencing
sSubs.type = '()';
sSubs.subs = repmat({':'}, 1, ndims(oStack));
% - Loop to perform sum in double precision
for (nIndex = 1:size(oStack, nDim))
sSubs.subs{nDim} = nIndex;
tfSlice = double(subsref(oStack, sSubs));
% - Ignore NaNs, if requested
if (bIgnoreNaNs)
if (~exist('tnNumNonNaNs', 'var'))
tnNumNonNaNs = zeros(size(tfSlice));
end
tnNumNonNaNs(~isnan(tfSlice)) = tnNumNonNaNs(~isnan(tfSlice)) + 1;
% - Set NaNs to zero
tfSlice(isnan(tfSlice)) = 0;
end
% - Perform sum
if (~exist('tfResult', 'var'))
tfResult = tfSlice;
else
tfResult = tfResult + tfSlice;
end
end
% - Cast result to native class, if necessary
if (strcmp(flag, 'native'))
tfResult = oStack.fhCastFun(tfResult);
end
end
% nansum - METHOD Overloaded nansum function
function tfResult = nansum(oStack, nDim)
if nargin == 1
nDim = find(size(oStack)~=1,1);
if isempty(nDim), nDim = 1; end
end
% - Call "sum" with "bIgnoreNaNs" set to true
tfResult = sum(oStack, nDim, 'default', true);
end
% mean - METHOD Overloaded mean function
function y = mean(x,dim,flag, bIgnoreNaNs)
if (~exist('bIgnoreNaNs', 'var'))
bIgnoreNaNs = true;
end
if nargin==2 && ischar(dim)
flag = dim;
elseif nargin < 3
flag = 'default';
end
if nargin == 1 || (nargin == 2 && ischar(dim))
dim = find(size(x)~=1,1);
if isempty(dim), dim = 1; end
end
% - Compute sum in double
[y, tnNumNonNaNs] = sum(x, dim, 'double', bIgnoreNaNs);
y = y ./ tnNumNonNaNs;
% - Re-cast result, if necessary
if (strcmp(flag, 'native'))
y = x.fhCastFun(y);
end
end
% nanmean - METHOD Overloaded nanmean
function y = nanmean(x,dim)
if nargin == 1
dim = find(size(x)~=1,1);
if isempty(dim), dim = 1; end
end
% - Call mean
y = mean(x,dim,'default', true);
end
%% --- Overloaded sort, prctile
% sort - METHOD Overloaded sort function
function tfSorted = sort(oStack, varargin)
% - Warn about loss of function
warning('TIFFStack:LostTIFFStack', '--- TIFFStack/sort: Warning: Data returned by ''sort'' is no longer a ''TIFFStack'' object.');
% - Set up referencing
sSubs.type = '()';
sSubs.subs = repmat({':'}, 1, ndims(oStack));
% - Just load stack and pass parameters to sort
tfSorted = sort(subsref(oStack, sSubs), varargin{:});
end
% prctile - METHOD Overloaded prctile function
function tfPrctile = prctile(oStack, varargin)
% - Warn about loss of function
warning('TIFFStack:LostTIFFStack', '--- TIFFStack/prctile: Warning: Data returned by ''prctile'' is no longer a ''TIFFStack'' object.');
% - Set up referencing
sSubs.type = '()';
sSubs.subs = repmat({':'}, 1, ndims(oStack));
% - Just load stack and pass parameters to sort
tfPrctile = prctile(subsref(oStack, sSubs), varargin{:});
end