Write multichannel (more than 4) tiff file, error using ExtraSamples tag
8 views (last 30 days)
Show older comments
I have a 5 channel image : R+G+B+NearInfraRed+ProcessedNearInfraRed. I need to save this in a tiff file. imwrite does not accept more than 4 channels so I used Tiff class (I am looking for something simple). I set the tags as below, but I get the error:
Error using tifflib
The combination of a photometric interpretation of RGB and a SamplesPerPixel value of 5
requires ExtraSamples to be properly set.
Here is the code I am trying to run.
t = Tiff([output_dir 'labelTEST' num2str(count) '.tiff'],'w');
t.setTag('Photometric',Tiff.Photometric.RGB);
t.setTag('Compression',Tiff.Compression.None);
t.setTag('BitsPerSample',8);
t.setTag('SamplesPerPixel',5);
t.setTag('SampleFormat',Tiff.SampleFormat.UInt);
t.setTag('ExtraSamples',Tiff.ExtraSamples.Unspecified);
t.setTag('ImageLength',size(I,2));
t.setTag('ImageWidth',size(I,1));
t.setTag('PlanarConfiguration',Tiff.PlanarConfiguration.Separate);
t.write(I);
t.close();
0 Comments
Answers (1)
Mann Baidi
on 23 Jul 2024
The error which you are facing is because, as per the TIFF file format specifications, the sum of number of Photometric color channels and the number of extraSamples should be equal to 'SamplesPerPixel'.
In the above example. RGB color space has 3 color channels while the 'SamplesPerPixel' has 5 color channels. This implies that are are two extra channels which need to be defined explicity using the ExtraSamples tag. You can define the extra channels using the following code:
t.setTag('ExtraSamples',[Tiff.ExtraSamples.Unspecified,Tiff.ExtraSamples.Unspecified]);
You can update your code as follows:
% Generate random data for the 5 channels
R = uint8(randi([0, 65535], 100, 100)); % Red channel
G = uint8(randi([0, 65535], 100, 100)); % Green channel
B = uint8(randi([0, 65535], 100, 100)); % Blue channel
IR = uint8(randi([0, 65535], 100, 100)); % Infrared channel
PNIR = uint8(randi([0, 65535], 100, 100)); % Processed Near Infrared channel
% Combine the channels into a 5-channel image
I = cat(3, R, G, B, IR, PNIR);
t = Tiff('example.tiff','w');
t.setTag('Photometric',Tiff.Photometric.RGB);
t.setTag('Compression',Tiff.Compression.None);
t.setTag('BitsPerSample',8);
t.setTag('SamplesPerPixel',5);
t.setTag('SampleFormat',Tiff.SampleFormat.UInt);
t.setTag('ExtraSamples',[Tiff.ExtraSamples.Unspecified,Tiff.ExtraSamples.Unspecified]);
t.setTag('ImageLength',size(I,2));
t.setTag('ImageWidth',size(I,1));
t.setTag('PlanarConfiguration',Tiff.PlanarConfiguration.Separate);
t.write(I);
t.close();
Hoping this would help!
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!