MATLAB Answers


Can imread input animated gifs written using imwrite?

Asked by Alec Jacobson on 14 Jun 2017
Latest activity Answered by Alec Jacobson on 14 Jun 2017

I've written an animated gif test.gif using imwrite:

frame = getframe(gcf);
[SIf,cm] = rgb2ind(frame.cdata,256);
frame = getframe(gcf);
[SIf,cm] = rgb2ind(frame.cdata,256);
imwrite(SIf,cm, 'test.gif','WriteMode','append','Delay',0.5);

If I try to read this back in using

[X,M] = imread('test.gif');

I see that X has 4 dimensions and the size of the fourth dimension is 2 (good, one for each frame). The colormap M has only 2 dimensions #colors by 3.

Plotting the first frame I see the correct image:


Plotting the second frame I see nonsense:


My guess is that the colormap is wrong/shouldn't be the same for every frame of the animation. Any idea what's going on here? The documentation for imread suggests that it should be able to handle animated gifs.


Sign in to comment.

1 Answer

Answer by Alec Jacobson on 14 Jun 2017

It seems like this is broken ... on purpose. In


There's a commented line:

% This only returns the color table for the first frame in the GIF file.
% There is an enhancement (g1055265) to make this return all color tables.
map = info.ColorTable;

I'm not sure why the map is set only to the first frame's colormap. If you're willing to modify built in matlab files then you can "fix" this so that map is a #colors by 3 by #frames matrix then change this line to:

map = reshape([info(:).ColorTable],[],3,n);


Sign in to comment.