从图像制作一个gif

时间:2013-06-20 15:30:06

标签: image matlab save matlab-figure animated-gif

我有100个.sdf文件(标记为0000.sdf到0099.sdf)的大量数据,每个文件都包含一个静止图像,我正在尝试从这些图像生成.gif文件。

我用来绘制图形的代码(与sdf文件位于同一目录中):

q = GetDataSDF('0000.sdf');
imagesc(q.data');

我试图编写一个for循环来绘制图形,然后使用与sdf文件相同的文件名保存它,但无效,使用:

for a = 1:100
    q=GetDataSDF('0000.sdf');
    fh = imagesc(q.dist_fn.x_px.Left.data');
    frm = getframe( fh );
    % save as png image
    saveas(fh, 'current_frame_%02d.jpg');
end

编辑:尝试运行此代码时收到以下错误:

Error using hg.image/get
The name 'Units' is not an accessible property for an instance of class 'image'.

Error in getframe>Local_getRectanglesOfInterest (line 138)
  if ~strcmpi(get(h, 'Units'), 'Pixels')

Error in getframe (line 56)
  [offsetRect, absoluteRect, figPos, figOuterPos] = ...

Error in loop_code (line 4)
    frm = getframe( fh );

如何使用for循环保存这些文件,然后如何使用这些文件制作电影?

1 个答案:

答案 0 :(得分:3)

错误的原因是您将图像句柄传递给getframe,但此函数会检测图形句柄。 另一个问题是你总是加载相同的文件,并且你的saveas不适用于GIF。 (为了将数字保存为静态图像,可能print是更好的选择吗?)

我尝试修改自己的gif-writing循环,以便它可以处理您的数据。我会尽量在评论中明确表达,因为你似乎已经开始了。请记住,您始终可以使用help name_of_command来显示简短的Matlab帮助。

% Define a variable that holds the frames per second your "movie" should have
gif_fps = 24; 
% Define string variable that holds the filename of your movie
video_filename = 'video.gif';

% Create figure 1, store the handle in a variable, you'll need it later
fh = figure(1);
for a = 0:99
    % Prepare file name so that you loop over the data
    q = GetDataSDF(['00' num2str(a,'%02d') 'sdf']);
    % Plot image
    imagesc(q.dist_fn.x_px.Left.data');
    % Force Matlab to actually do the plot (it sometimes gets lazy in loops)  
    drawnow;
    % Take a "screenshot" of the figure fh
    frame = getframe(fh);
    % Turn screenshot into image
    im = frame2im(frame);
    % Turn image into indexed image (the gif format needs this)
    [imind,cm] = rgb2ind(im,256);
    % If first loop iteration: Create the file, else append to it
    if a == 0;
        imwrite(imind,cm,video_filename,'gif', 'Loopcount',inf);
    else
        imwrite(imind,cm,video_filename,'gif','WriteMode','append','DelayTime',1/gif_fps);
    end
end

还有一点需要注意:当每个绘图的数据大小相同时,仅使用plot(或在本例中为imagesc)命令一次,以及稍后使用循环迭代用set(ah,'Ydata',new_y_data)替换它(或者在这种情况下set(ah,'CData',q.dist_fn.x_px.Left.data'),其中ah是绘图的句柄(不是绘图!)。这比在每次循环迭代中创建一个全新的绘图快几个数量级。缺点是每个绘图的缩放(这里,颜色缩放)将是相同的。但是在每种情况下到目前为止我一直在努力,这实际上是可取的。