forked from DylanMuir/TIFFStack
-
Notifications
You must be signed in to change notification settings - Fork 0
/
TIFFStack.m
executable file
·1311 lines (1095 loc) · 49.7 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
% TIFFStack - Manipulate a TIFF file like a tensor
%
% Usage: tsStack = TIFFStack(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: 10.3389/fninf.2014.00085
%
% 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 [1, 2] 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);
%
% -------------------------------------------------------------------------
%
% Construction:
%
% >> 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
%
% -------------------------------------------------------------------------
%
% De-interleaving frame dimensions in complex stacks
%
% 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.
%
% -------------------------------------------------------------------------
%
% References:
% [1] Francois Nedelec, Thomas Surrey and A.C. Maggs. Physical Review Letters
% 86: 3192-3195; 2001. DOI: 10.1103/PhysRevLett.86.3192
%
% [2] http://www.embl.de/~nedelec/
% Author: Dylan Muir <[email protected]>
% Created: 28th June, 2011
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)
vnDataSize; % - Cached size of the TIFF stack
vnApparentSize; % - Apparent size of the TIFF stack
TIF; % \_ Cached header info for tiffread29 speedups
HEADER; % /
bUseTiffLib; % - Flag indicating whether TiffLib 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 permution
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
% - 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 save image information
sInfo = imfinfo(strFilename);
oStack.sImageInfo = sInfo;
if (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 casting function
oStack.fhCastFun = str2func(oStack.strDataClass);
% -- 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 (nRowsPerStrip ~= oStack.sImageInfo(1).RowsPerStrip)
[oStack.sImageInfo.RowsPerStrip] = deal(nRowsPerStrip);
end
else
% - Read TIFF header for tiffread29
[oStack.TIF, oStack.HEADER] = tiffread29_header(strFilename);
% - Use tiffread29 to get the data class for this tiff
fPixel = tiffread29_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);
% - Record stack size
oStack.vnDataSize = [sInfo(1).Height sInfo(1).Width numel(sInfo) sInfo(1).SamplesPerPixel];
% - 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)];
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)];
end
% - Initialise dimension order
oStack.vnDimensionOrder = 1:numel(oStack.vnApparentSize);
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
else
% - Close the TIFF file, if opened by tiffread29_header
if (isfield(oStack.TIF, 'file'))
fclose(oStack.TIF.file);
end
end
end
% diagnostic - METHOD Display some diagnostics about a stack
function diagnostic(oStack)
disp(oStack);
fprintf('<strong>Private properties:</strong>\n');
fprintf(' bUseTiffLib: %d\n', oStack.bUseTiffLib);
fprintf(' fhReadFun: %s\n', func2str(oStack.fhReadFun));
fprintf(' vnDimensionOrder: ['); fprintf('%d ', oStack.vnDimensionOrder); fprintf(']\n');
fprintf(' fhRepSum: %s\n', func2str(oStack.fhRepSum));
end
%% --- Overloaded subsref
function [tfData] = 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
vnInvOrder(oStack.vnDimensionOrder(1:nNumNZStackDims)) = 1:nNumNZStackDims;
S.subs = S.subs(vnInvOrder(vnInvOrder ~= 0));
S.subs(nNumNZStackDims+1:nNumTotalStackDims) = {1};
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)
tfData = 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) {vnFrameIndices(:)} S.subs(end)];
end
end
% - Access stack (tifflib or tiffread)
if (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
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 bInvert = getInvert(oStack)
bInvert = oStack.bInvert;
end
function strDataClass = getDataClass(oStack)
strDataClass = oStack.strDataClass;
end
%% --- Overloaded numel, size, permute, ipermute, ctranspose, transpose
function [n] = numel(oStack)
n = prod(size(oStack)); %#ok<PSIZE>
end
function [varargout] = size(oStack, vnDimensions)
% - Get original tensor size, and extend dimensions if necessary
vnApparentSize = oStack.vnApparentSize; %#ok<PROP>
vnApparentSize(end+1:numel(oStack.vnDimensionOrder)) = 1; %#ok<PROP>
% - Return the size of the tensor data element, permuted
vnSize = vnApparentSize(oStack.vnDimensionOrder); %#ok<PROP>
% - Trim trailing unitary dimensions
vbIsUnitary = vnSize == 1;
if (vbIsUnitary(end))
nLastNonUnitary = find(vnSize == 1, 1, 'last') - 1;
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
% 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
%% --- 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
%% --- Property accessors
% set.bInvert - SETTER method for 'bInvert'
function set.bInvert(oStack, bInvert)
% - Check contents
if (~islogical(bInvert) || ~isscalar(bInvert))
error('TIFFStack:InvalidArgument', ...
'*** TIFFStack/set.bInvert: ''bInvert'' must be a logical scalar.');
else
% - Assign bInvert value
oStack.bInvert = bInvert;
end
end
end
end
%% --- Helper functions ---
% TS_read_data_tiffread - FUNCTION Read the requested pixels from the TIFF file (using tiffread29)
%
% Usage: [tfData] = TS_read_data_imread(oStack, cIndices)
%
% 'oStack' is a TIFFStack. 'cIndices' are the indices passed in from subsref.
% Colon indexing will be converted to full range indexing. cIndices is a cell
% array with the format {rows, cols, frames, slices}. Slices are RGB or CMYK
% or so on.
function [tfData] = TS_read_data_tiffread(oStack, cIndices, bLinearIndexing)
% - Fix up final index dimensions, if necessary
cIndices(end+1:4) = {1};
% - Convert colon indexing
vbIsColon = cellfun(@iscolon, cIndices);
for (nColonDim = find(vbIsColon))
cIndices{nColonDim} = 1:oStack.vnDataSize(nColonDim);
end
% - Fix up subsample detection for unitary dimensions
vbIsOne = cellfun(@(c)isequal(c, 1), cIndices);
vbIsColon(~vbIsColon) = vbIsOne(~vbIsColon) & (oStack.vnDataSize(~vbIsColon) == 1);
% - Check ranges
vnMinRange = cellfun(@(c)(min(c(:))), cIndices(~vbIsColon));
vnMaxRange = cellfun(@(c)(max(c(:))), cIndices(~vbIsColon));
if (any(vnMinRange < 1) || any(vnMaxRange > oStack.vnDataSize(~vbIsColon)))
error('TIFFStack:badsubscript', ...
'*** TIFFStack: Index exceeds stack dimensions.');
end
% - Find unique frames to read
[vnFrameIndices, ~, vnOrigFrameIndices] = unique(cIndices{3});
% - Read data block
try
tfDataBlock = tiffread29_readimage(oStack.TIF, oStack.HEADER, vnFrameIndices);
catch mErr
% - Record error state
base_ME = MException('TIFFStack:ReadError', ...
'*** TIFFStack: Could not read data from image file.');
new_ME = addCause(base_ME, mErr);
throw(new_ME);
end
% - Handle linear or subscript indexing
if (~bLinearIndexing)
% - Select pixels from frames, if necessary
if any(~vbIsColon([1 2 4]))
tfData = tfDataBlock(cIndices{1}, cIndices{2}, vnOrigFrameIndices, cIndices{4});
else
tfData = tfDataBlock;
end
else
% - Convert frame indices to frame-linear
vnFrameLinearIndices = sub2ind(oStack.vnDataSize([1 2 4]), cIndices{1}, cIndices{2}, cIndices{4});
% - Allocate return vector
tfData = zeros(numel(cIndices{1}), 1, oStack.strDataClass);
% - Loop over images in stack and extract required frames
for (nFrameIndex = 1:numel(vnFrameIndices))
vbThesePixels = cIndices{3} == vnFrameIndices(nFrameIndex);
mfThisFrame = tfDataBlock(:, :, nFrameIndex, :);
tfData(vbThesePixels) = mfThisFrame(vnFrameLinearIndices(vbThesePixels));
end
end
% - Invert data if requested
if (oStack.bInvert)
tfData = oStack.fhCastFun(oStack.sImageInfo(1).MaxSampleValue) - (tfData - oStack.fhCastFun(oStack.sImageInfo(1).MinSampleValue));
end
end
% TS_read_data_Tiff - FUNCTION Read the requested pixels from the TIFF file (using tifflib)
%
% Usage: [tfData] = TS_read_data_Tiff(oStack, cIndices)
%
% 'oStack' is a TIFFStack. 'cIndices' are the indices passed in from subsref.
% Colon indexing will be converted to full range indexing. cIndices is a cell
% array with the format {rows, cols, frames, slices}. Slices are RGB or CMYK
% or so on.
function [tfData] = TS_read_data_Tiff(oStack, cIndices, bLinearIndexing)
% - Convert colon indexing
vbIsColon = cellfun(@iscolon, cIndices);
for (nColonDim = find(vbIsColon))
cIndices{nColonDim} = 1:oStack.vnDataSize(nColonDim);
end
% - Fix up subsample detection for unitary dimensions
vbIsOne = cellfun(@(c)isequal(c, 1), cIndices(~vbIsColon));
vbIsColon(~vbIsColon) = vbIsOne & (oStack.vnDataSize(~vbIsColon) == 1);
% - Check ranges
vnMinRange = cellfun(@(c)(min(c(:))), cIndices(~vbIsColon));
vnMaxRange = cellfun(@(c)(max(c(:))), cIndices(~vbIsColon));
if (any(vnMinRange < 1) || any(vnMaxRange > oStack.vnDataSize(~vbIsColon)))
error('TIFFStack:badsubscript', ...
'*** TIFFStack: Index exceeds stack dimensions.');
end
% - Get referencing parameters for TIF object
w = oStack.vnDataSize(2);
h = oStack.vnDataSize(1);
rps = min(oStack.sImageInfo(1).RowsPerStrip, h);
tw = min(oStack.sImageInfo(1).TileWidth, w);
th = min(oStack.sImageInfo(1).TileLength, h);
spp = oStack.sImageInfo(1).SamplesPerPixel;
tlStack = oStack.TIF;
% - Handle linear or subscript indexing
if (~bLinearIndexing)
% - Allocate single frame buffer
vnBlockSize = oStack.vnDataSize(1:2);
vnBlockSize(3) = numel(cIndices{3});
vnBlockSize(4) = oStack.vnDataSize(4);
tfImage = zeros([vnBlockSize(1:2) 1 vnBlockSize(4)], oStack.strDataClass);
% - Allocate tensor for returning data
vnOutputSize = cellfun(@(c)numel(c), cIndices);
tfData = zeros(vnOutputSize, oStack.strDataClass);
% - Do we need to resample the data block?
vbTest = [true true false true];
bResample = any(vbTest(~vbIsColon));
try
% - Loop over images in stack
for (nImage = 1:numel(cIndices{3}))
% - Skip to this image in stack
oStack.fhSetDirFun(tlStack, cIndices{3}(nImage));
% - Read data from this image, overwriting frame buffer
[~, tfImage] = oStack.fhReadFun(tfImage, tlStack, spp, w, h, rps, tw, th, []);
% - Resample frame, if required
if (bResample)
tfData(:, :, nImage, :) = tfImage(cIndices{1}, cIndices{2}, cIndices{4});
else
tfData(:, :, nImage, :) = tfImage;
end
end
catch mErr
% - Record error state
base_ME = MException('TIFFStack:ReadError', ...
'*** TIFFStack: Could not read data from image file.');
new_ME = addCause(base_ME, mErr);
throw(new_ME);
end
else
% -- Linear indexing
% - Allocate return vector
tfData = zeros(size(cIndices{1}), oStack.strDataClass);
% - Allocate single-frame buffer
vnBlockSize = oStack.vnDataSize(1:2);
vnBlockSize(3) = numel(cIndices{3});
vnBlockSize(4) = oStack.vnDataSize(4);
tfImage = zeros([vnBlockSize(1:2) 1 vnBlockSize(4)], oStack.strDataClass);
% - Convert frame indices to frame-linear
vnFrameLinearIndices = sub2ind(vnBlockSize([1 2 4]), cIndices{1}, cIndices{2}, cIndices{4});
% - Loop over images in stack and extract required frames
try
for (nImage = unique(cIndices{3}(:))')
% - Find corresponding pixels
vbThesePixels = cIndices{3} == nImage;
% - Skip to this image in stack
oStack.fhSetDirFun(tlStack, nImage);
% - Read the subsampled pixels from the stack
[tfData(vbThesePixels), tfImage] = oStack.fhReadFun(tfImage, tlStack, spp, w, h, rps, tw, th, vnFrameLinearIndices(vbThesePixels));
end
catch mErr
% - Record error state
base_ME = MException('TIFFStack:ReadError', ...
'*** TIFFStack: Could not read data from image file.');
new_ME = addCause(base_ME, mErr);
throw(new_ME);
end
end
% - Invert data if requested
if (oStack.bInvert)
tfData = oStack.sImageInfo(1).MaxSampleValue(1) - (tfData - oStack.sImageInfo(1).MinSampleValue(1));
end
end
% GetLinearIndicesForRefs - FUNCTION Convert a set of multi-dimensional indices directly into linear indices
function [vnLinearIndices, vnDimRefSizes] = GetLinearIndicesForRefs(cRefs, vnLims, hRepSumFunc)
% - Find colon references
vbIsColon = cellfun(@iscolon, cRefs);
if (all(vbIsColon))
vnLinearIndices = 1:prod(vnLims);
vnDimRefSizes = vnLims;
return;
end
nFirstNonColon = find(~vbIsColon, 1, 'first');
vbTrailingRefs = true(size(vbIsColon));
vbTrailingRefs(1:nFirstNonColon-1) = false;
vnDimRefSizes = cellfun(@numel, cRefs);
vnDimRefSizes(vbIsColon) = vnLims(vbIsColon);
% - Calculate dimension offsets
vnDimOffsets = [1 cumprod(vnLims)];
vnDimOffsets = vnDimOffsets(1:end-1);
% - Remove trailing "1"s
vbOnes = cellfun(@(c)isequal(c, 1), cRefs);
nLastNonOne = find(~vbOnes, 1, 'last');
vbTrailingRefs((nLastNonOne+1):end) = false;
% - Check reference limits
if (any(cellfun(@(r,l)any(r>l), cRefs(~vbIsColon), num2cell(vnLims(~vbIsColon)))))
error('TIFFStack:badsubscript', 'Index exceeds matrix dimensions.');
end
% - Work out how many linear indices there will be in total
nNumIndices = prod(vnDimRefSizes);
vnLinearIndices = zeros(nNumIndices, 1);
% - Build a referencing window encompassing the leading colon refs (or first ref)
if (nFirstNonColon > 1)
vnLinearIndices(1:prod(vnLims(1:(nFirstNonColon-1)))) = 1:prod(vnLims(1:(nFirstNonColon-1)));
else
vnLinearIndices(1:vnDimRefSizes(1)) = cRefs{1};
vbTrailingRefs(1) = false;
end
% - Replicate windows to make up linear indices
for (nDimension = find(vbTrailingRefs & ~vbOnes))
% - How long is the current window?
nCurrWindowLength = prod(vnDimRefSizes(1:(nDimension-1)));
nThisWindowLength = nCurrWindowLength * vnDimRefSizes(nDimension);
% - Is this dimension a colon reference?
if (vbIsColon(nDimension))
vnLinearIndices(1:nThisWindowLength) = hRepSumFunc(vnLinearIndices(1:nCurrWindowLength), ((1:vnLims(nDimension))-1) * vnDimOffsets(nDimension));
else
vnLinearIndices(1:nThisWindowLength) = hRepSumFunc(vnLinearIndices(1:nCurrWindowLength), (cRefs{nDimension}-1) * vnDimOffsets(nDimension));
end
end
end
% mapped_tensor_repsum_nomex - FUNCTION Slow version of replicate and sum
function [vfDest] = mapped_tensor_repsum_nomex(vfSourceA, vfSourceB)