Save a stack of 16-bit images to one TIFF file
15 views (last 30 days)
Show older comments
Hi,
I would like to save a stack (in this case 150) of uint16 grayscale images to a single TIFF-file. First I tried pass over the 3D-array (the third dimension are the individual images) to imwrite, but it complained "Writing TIFFs with 150 components is not supported with IMWRITE. Use Tiff instead. ". I tried this (imgdata is my 3D-array of images):
imgdata = uint16(imgdata);
tagstruct.ImageLength = size(imgdata,1);
tagstruct.ImageWidth = size(imgdata,2);
tagstruct.Photometric = Tiff.Photometric.MinIsBlack;
tagstruct.BitsPerSample = 16;
tagstruct.SamplesPerPixel = 1;
tagstruct.PlanarConfiguration = Tiff.PlanarConfiguration.Chunky;
tagstruct.Software = 'MATLAB';
tagstruct.Compression = 1;
t = Tiff(path,'w');
setTag(t,tagstruct);
write(t,imgdata);
I got the error message "SamplesPerPixel is 1, but the number of image planes provided was 150.", so write() interprets the third dimension as the samples per pixel, which is not what I want. Samples per Pixel needs to be 1, as I have grayscale images.
After that, I also tried it with the "append" option and a loop over the images (with the same tagstruct as above)
t = Tiff(path,'a');
setTag(t,tagstruct);
numberOfImages = size(imgdata,3);
for n=1:numberOfImages
currentImage = squeeze(imgdata(:,:,n));
write(t,currentImage);
end
close(t);
It runs without errors and the file size of the uncompressed file is exactly what I would expect, so I think the data is in the file. But I can't open the file in any other software than matlab. Irfanview, imageJ, Windows image viewer all show just the first image of the stack.
Any ideas what's wrong? Thanks.
0 Comments
Answers (1)
Mann Baidi
on 24 Jul 2024
The TIFF file which you are creating using the code mentioned above has only one frame/directory. This the reason why you are seeing only one image.
Assuming you would like to create a multi-layer TIFF file, you will have to create a new image file directory (IFD) using the 'writeDirectory()' function after every loop.
You can update yoy for loop function as follow:
for n=1:numberOfImages
t.setTag(tagstruct);
currentImage = squeeze(imgdata(:,:,n));
write(t,currentImage);
writeDirectory(t);
end
You can learn about the 'writeDirectory()' function by clicking on the link mentioned below:
0 Comments
See Also
Categories
Find more on Image Data in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!