Search code examples
matlabtiffimread

Saving an int16 stacked tif in matlab


I'm trying to save a .tif in matlab. Imwrite doesn't support writing int16 directly for .tif, but it is possible to cast my picture to uint16 and use imwrite.

imageName='someimage.tif';
info=imfinfo(imageName);
num_images=numel(info);
x_size=info(1).Width;
y_size=info(1).Height;

result=zeros(y_size, x_size, num_images, 'uint16');
for i=1:num_images
    result(:,:,i) = im2uint16(imread(imageName,i,'Info',info));
end

imwrite(result(:,:,i), 'newimage.tif');
for i=2:num_images,
    imwrite(result(:,:,i), 'newimage.tif', 'WriteMode', 'append');
end

When I do this it seems like the contrast is increased somehow, while I would expect the pictures to be identical.

Secondly I tried using this as following

imageName='someimage.tif';
info=imfinfo(imageName);
num_images=numel(info);
x_size=info(1).Width;
y_size=info(1).Height;

result=zeros(y_size, x_size, num_images, 'int16');
for i=1:num_images
    result(:,:,i) = imread(imageName,i,'Info',info);
end
options.message=true;
saveastiff(result, 'newimage.tif', options);

I have the same issue here, the contrast goes up and it ruins the picture. The pictures I am working on a grayscale. Is there a way to save these pictures without ruining it?


Solution

  • @siliconwafer helped me understand that my problem is that the first few frames are fairly bright and the rest of the pictures appear black if you use the same dynamic range as for the first picture.

    I was not able to solve this in an eloquent way, but I did the following

    t = Tiff("Some_image.tif", 'r+');
    imgs = zeros(y_size, x_size, num_images, 'uint16');
    for k=1:num_images,
        t.setDirectory(k);
        imgs(:,:,k) = t.read();
    end
    
    result = doStuff(imgs)
    
    for k=1:num_images,
        t.setDirectory(k);
        t.write(imgs(:,:,k));
    end
    

    The downside of this is that it changes the picture in place. The advantage is that the dynamic range for each frame does not change.