How to read an animated gif with alpha channel

后端 未结 1 1927
北恋
北恋 2020-12-31 05:53

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

Example:

(Original source

相关标签:
1条回答
  • 2020-12-31 06:15

    /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
    
    0 讨论(0)
提交回复
热议问题