Create high-quality animated, color, looping gif in Matlab

Alec Jacobson

December 19, 2013

weblog/

Writing GIFs in matlab is a bit of a pain. Assuming you have a sequence of RGB images stored in a Height-by-Width-by-3-NumberOfFrames matrix S, then you can write this as an animation with no delay to a .gif file using:

filename = 'foobar.gif';
for f = 1:size(S,4)
  [SIf,cm] = rgb2ind(S(:,:,:,f),256);
  if f == 1
    imwrite(SIf,cm,filename,'Loop',Inf,'Delay',0);
  else
    imwrite(SIf,cm, filename,'WriteMode','append','Delay',0);
  end
end

Update: Often instead of S(:,:,:,f) I'll have my frames coming from a figure window:

  frame = getframe(gcf);
  [SIf,cm] = rgb2ind(frame.cdata,256);