Clear Filters
Clear Filters

I cannot read the last image of a multipage tiff created in Matlab.

5 views (last 30 days)
I receive the error below when attempting to access the last image in a multipage Tiff file I have written in Matlab. I can access all the other directories. Thank you for any suggestions or explanations.
Error using tifflib
Unable to change to directory with dirnum = 3.
Error in Tiff/setDirectory (line 1277)
tifflib('setDirectory',obj.FileID,dirNum-1);
The code below duplicates the issue I am having.
t=Tiff('test.tiff','w');%initialize tiff
testImage=ones(10,'uint16');%data to write
tagstruct.ImageLength = 10;
tagstruct.ImageWidth = 10;
tagstruct.Photometric = Tiff.Photometric.MinIsBlack;
tagstruct.BitsPerSample = 16;
tagstruct.SamplesPerPixel = 1;
tagstruct.Compression = Tiff.Compression.PackBits;
tagstruct.PlanarConfiguration = Tiff.PlanarConfiguration.Chunky;
%begin writing tiff
%image 1
t.setTag(tagstruct);
t.write(testImage);
%image 2
t.writeDirectory();
t.setTag(tagstruct);
t.write(testImage+1);
%image 3
t.writeDirectory();
t.setTag(tagstruct);
t.write(testImage+2);
%go back to each image and read out the values there
%the value should correspond to the image number
t.setDirectory(1);
testImageOut=t.read();
disp(['image value: ',num2str(max(testImageOut(:)))]);
t.setDirectory(2);
testImageOut=t.read();
disp(['image value: ',num2str(max(testImageOut(:)))]);
t.setDirectory(3);
testImageOut=t.read();
disp(['image value: ',num2str(max(testImageOut(:)))]);
The output from this is:
image value: 1
image value: 2
Error using tifflib
Unable to change to directory with dirnum = 3.
Error in Tiff/setDirectory (line 1277)
tifflib('setDirectory',obj.FileID,dirNum-1);

Answers (1)

Mann Baidi
Mann Baidi on 23 Jul 2024
Hi @Kalen,
You are getting the error because there are are only 2 IFD in the TIFF file mentioned above. You called writeDirectory two times, hence only 2 directories are being created.
You can check the number of IFD in a TIFF image using the following code:
info=imfinfo('<filename>.tiff');
numel(info)
You can explore more about imfinfo function using the below link:

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!