使用LeaveInPlace处理方法读取具有透明度或Alpha通道的动画GIF

时间:2016-05-15 19:29:25

标签: matlab gif animated-gif

当我读到这个GIF,然后用imshow(I(:,:,:,2),map);显示它时,gif框架上有污点,我想这可能是因为GIF处理方法。怎么处理呢?

intended, animated gif

[I map]=imread('smile.gif');

这就是我得到的。

my result, with stains

1 个答案:

答案 0 :(得分:1)

使用以下代码与带alpha通道的动画gif的imshow第2帧。

在这里,只有gif的第一帧有完整的笑脸图像,笑脸的背景包含TransparentColor。在其余帧中,一些笑脸像素也被设置为TransparentColor。因此,要获得其他帧,您必须使用前一帧的rgb图像中的像素替换TransparentColor像素。这就像将所需的帧放在前一帧的顶部以获得完整的图像。

% which frame to show
frame=2;

% filename of gif image
filename='smile.gif';

% Reading gif image
[I map]=imread(filename);

% get information from graphics file( we need the TransparentColor 
% and ColorTable of the gif)
info=imfinfo(filename);

% Set the transparent color to what ever color you like. 
% Because this will be the background color for frame 1 and this
% will be copied to the next frames.
info(1).ColorTable(TransparentColor,:)=[1 1 1];
% RGB Image of first frame
im_new=ind2rgb(I(:,:,:,1),info(1).ColorTable);

% loop from second to the required frame
for frameIndex=2:frame
% get information from graphics file( we need the TransparentColor 
% and ColorTable of the gif)
info=imfinfo(filename);    

% Get the transparentColor of current frame
TransparentColor=info(frameIndex).TransparentColor;

% Change that transparentColor in the map to [NaN NaN NaN]
info(frameIndex).ColorTable(TransparentColor,:)=[NaN NaN NaN];

% Generate rgb image with I and modified color table
imNaN=ind2rgb(I(:,:,:,frameIndex),info(frameIndex).ColorTable);

% We are setting it as [NaN NaN NaN] because then we can find 
% thoses transparent pixels using 'isnan(imNaN)'. 

% Change that transparentColor in the map to [0 0 0] and generate 
% another rgb image
info(frameIndex).ColorTable(TransparentColor,:)=[0 0 0];
im=ind2rgb(I(:,:,:,frameIndex),info(frameIndex).ColorTable);

% 'im' will have [0 0 0] in pixel places of [NaN NaN NaN].
% We are putting zero here because then we can find where there 
% is NaN in 'imNaN' and get those pixels from the previous rgb frame and 
% add thoses with the zero in 'im'.

% copy the previous rgb frame to 'im0'
im0=im_new;

% Now as said before we are going to find the pixels with 
% 'NaN' present using 'isnan(imNaN)' this will be one or zero 
% for each pixel. If the pixel is 'NaN' then 'one' otherwise 'zero'.
% Now we mutiply this with the coresponding pixel in frame one. If the
% pixel is not 'NaN' then the product will zero otherwise pixel 
% value of im0. We add this to 'im'. Which has 'zero' instead of 'NaN'. 
% The result will be, where there is 'NaN', pixel from 'im0' is copied 
% to im_new otherwise 'im_new' will have 'im'.
im_new=((isnan(imNaN).*im0))+im;

% This is repeated till the required frame is reached
end

% show image
imshow(im_new);

因为这个gif的像素是透明的。在这里,我用白色填充透明部分。如果您需要在

中使用不同的颜色更改[1 1 1]
info(1).ColorTable(TransparentColor,:)=[1 1 1];

到所需的值。每个值都与0 to 1不同。其中0表示完全没有该颜色成分,1表示该颜色成分完全存在。对于颜色之间使用十进制值(0.25,0.7,......等)