MATLAB Answers

1

How to save a Tiff using signed values with LibTiff library.

Asked by Katherine on 17 Nov 2014
Latest activity Commented on by Katherine on 17 Nov 2014
I am using the LibTiff library, as I already know that imwrite can't deal with signed values. If I try to convert FinalImage to int16 before saving it, I get the following error message:
Error using tifflib If SampleFormat is Uint, the image datatype is restricted to one of the following: logical, uint8, uint16, uint32.
Error in Tiff/writeAllStrips (line 1933) tifflib('writeEncodedStrip',obj.FileID, stripNum-1,imageData(row_inds,:));
Error in Tiff/write (line 1459) obj.writeAllStrips(varargin{:});
Error in tiffsaveexample (line 33) t.write(intFinalImage(:,:,1));
So it seems that I must change this variable SampleFormat, but I don't know how to modify this. Any recommendations?
This results from the follwing code:
% Save tiff unsigned attempt
FileTif='11_7_blank1_avgentire_stack_bck.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);
tiffFile = strcat('bksub2_', FileTif);
t = Tiff(tiffFile,'w')
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(:,:,1));
t.close();

  0 Comments

Sign in to comment.

1 Answer

Answer by Ashish Uthama on 17 Nov 2014
Edited by Ashish Uthama on 17 Nov 2014
 Accepted Answer

You need one extra tag:
intFinalImage = int16(magic(10));
tiffFile = 't.tif';
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(:,:,1));
t.close();
d = imread(tiffFile);
class(d)
ans =
int16

  1 Comment

This fixes it! Thank you so much for your help!

Sign in to comment.