MATLAB: Efficiently saving multislice tiff using Tifflib

saving stackssaving tiffstifftifflib

I am trying to use the Tiff(*.tif, 'w') function to save a tiff with multiple frames/slices. The code that I have works, but takes a while to run, especially when I try to use it on 400+ slice tiffs. I have only been able to save multislice tiffs using this rather clunky set of for loops. If I try to write the entire thing at once, I end up with a one slice tiff file that contains all of the slices overlaid on top of each other. If anyone has encountered this problem, or knows a solution I would appreciate it.
Here is the code I have:
FileTif='11_7_dimer_1E4_s1_8_20slice.tif';
InfoImage=imfinfo(FileTif);
mImage=InfoImage(1).Width;
nImage=InfoImage(1).Height;
NumberImages=length(InfoImage);
FinalImage=zeros(nImage,mImage,NumberImages,'uint16');
TifLink = Tiff(FileTif, 'r');
for i=1:NumberImages
TifLink.setDirectory(i);
FinalImage(:,:,i)=TifLink.read();
end
TifLink.close();
intFinalImage = int16(FinalImage);
for numin = 1:NumberImages
tiffFile = strcat('bksub_', FileTif);
for numin = 1
t = Tiff(tiffFile,'w')
tagstruct.SampleFormat = Tiff.SampleFormat.Int;
tagstruct.ImageLength = size(intFinalImage,1);
tagstruct.ImageWidth = size(intFinalImage,2);
tagstruct.Photometric = Tiff.Photometric.MinIsBlack;
tagstruct.BitsPerSample = 16;
tagstruct.SamplesPerPixel = 1;
tagstruct.RowsPerStrip = 16;
tagstruct.PlanarConfiguration = Tiff.PlanarConfiguration.Chunky
tagstruct.Software = 'MATLAB';
t.setTag(tagstruct);
t.write(intFinalImage(:,:,numin));
t.close();
end
for numin = 2:NumberImages;
t = Tiff(tiffFile, 'a');
tagstruct.SampleFormat = Tiff.SampleFormat.Int;
tagstruct.ImageLength = size(intFinalImage,1);
tagstruct.ImageWidth = size(intFinalImage,2);
tagstruct.Photometric = Tiff.Photometric.MinIsBlack;
tagstruct.BitsPerSample = 16;
tagstruct.SamplesPerPixel = 1;
tagstruct.RowsPerStrip = 16;
tagstruct.PlanarConfiguration = Tiff.PlanarConfiguration.Chunky
tagstruct.Software = 'MATLAB';
t.setTag(tagstruct);
t.write(intFinalImage(:,:,numin));
t.close();
end
end

Best Answer

Does this help?