How to read an animated gif with alpha channel

三世轮回 提交于 2019-12-18 12:54:38

问题


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 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)):

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?


回答1:


/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


来源:https://stackoverflow.com/questions/34970064/how-to-read-an-animated-gif-with-alpha-channel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!