Ander Biguri
Ander Biguri

Reputation: 35525

How to read an animated gif with alpha channel

While doing some tests with .gif animations in MATLAB I realised that somehow I can't read the transparency of the gif.

Example:

enter image description here

(Original source of the gif)

If I do

[img,cmap]=imread('Finnandjake.gif');

img is 4D with a redundant 3rd dimension (weird). After squeezing it (img=squeeze(img);), if I show it (imshow(img(:,:,30),cmap)):

enter image description here

The transparency is gone, using another color from the image as background, thus deleting features. However

[img,cmap,alpha]=imread('Finnandjake.gif');

returns an empty alpha. Obviously the information of the alpha is in the image somewhere, how can I read it in MATLAB?

Upvotes: 15

Views: 2049

Answers (1)

Daniel
Daniel

Reputation: 36710

/Update: I made the code available at MATLAB file exchange. The published version is compatible to OCTAVE and comes with some documentation.


I came up with this solution. Return arguments are the stacked images, the colormap and the index corresponding to transparency.

%do not use, instead use: http://www.mathworks.com/matlabcentral/fileexchange/55693-transparentgifread-filename-
function [stack,map,transparent]=transparentGifRead(filename)
if ~exist(filename,'file')
    error('file %s does not exist',filename);
end
info=imfinfo(filename);
%Check if color map for all frames is the same
if any(any(any(diff(cat(3,info.ColorTable),[],3))))
    error('inconsistent color map')
else
    map=info(1).ColorTable;
end
%Check if transparent color for all frames is the same
if any(diff([info.TransparentColor]))
    error('inconsistent transparency information')
else
    transparent=info(1).TransparentColor-1;
end
import java.io.*
str = javax.imageio.ImageIO.createImageInputStream(java.io.File(filename));
t = javax.imageio.ImageIO.getImageReaders(str);
reader = t.next();
reader.setInput(str);
numframes = reader.getNumImages(true);
for imageix = 1:numframes
    data = reader.read(imageix-1).getData();
    height = data.getHeight();
    width = data.getWidth();
    data2 = reader.read(imageix-1).getData().getPixels(0,0,width,height,[]);
    if imageix == 1
        stack=zeros(height,width,1,numframes,'uint8');
    end
    %row major vs column major fix
    stack(:,:,1,imageix) = reshape(data2,[width height]).';%'
end
str.close();
end

Some demonstration code to colour the transparent pixels green:

[stack,map,transparent]=transparentGifRead('tr.gif');
map(transparent+1,:)=[0,1,0] %offset 1 because uint8 starts at 0 but indices at 1
for frame=1:size(stack,ndims(stack))
    imshow(stack(:,:,frame),map);
    pause(1/25);
end

Upvotes: 9

Related Questions