如何阅读带有 alpha 通道的动画 gif

How to read an animated gif with alpha channel

在 MATLAB 中使用 .gif 动画进行一些测试时,我意识到我无法以某种方式读取 gif 的透明度。

示例:

(Original source of the gif)

如果我这样做

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

img 是 4D,具有冗余的第 3 维(很奇怪)。挤压后(img=squeeze(img);),如果我显示它(imshow(img(:,:,30),cmap)):

透明度消失了,使用图像中的另一种颜色作为背景,从而删除了特征。不过

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

returns 空 alpha。很明显alpha的信息在图像的某处,我如何在MATLAB中读取它?

/更新:我在 MATLAB file exchange 提供了代码。发布的版本与 OCTAVE 兼容,并附带一些文档。


我想到了这个解决方案。 Return 参数是堆叠图像、颜色图和与透明度对应的索引。

%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

将透明像素着色为绿色的一些演示代码:

[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