image - 从图像制作 gif

标签 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 循环保存这些文件,以及如何使用这些文件来制作电影?

最佳答案

错误的原因是您将图像句柄传递给 getframe ,但此函数需要一个图形句柄。 另一个问题是您总是加载相同的文件,并且您的保存方式不适用于 gif。 (要将图形保存为静态图像,也许 print 是更好的选择?)

我尝试修改我自己的 gif 写入循环,以便它可以处理您的数据。我会尽量在评论中更加明确,因为你似乎才刚刚开始。请记住,您始终可以使用 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 是绘图轴的句柄(不是绘图图!)。这比创建速度快几个数量级每次循环迭代中都会有一个全新的绘图。缺点是每个绘图的缩放(此处为颜色缩放)都是相同的。但到目前为止,在我处理过的每种情况下,这实际上都是可取的。

关于image - 从图像制作 gif,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17217774/

相关文章:

android - 连接来自 Canny 算法的线

java - 组件位置 (Vaadin)

ios - 调整图像选定区域的大小

matlab - 为什么 surf 函数中 Z 尺寸相反

python - 如何在Matlab或Python中移动由零内切的矩形数组?

asp.net - 在数据库中存储一个全局计数器?还有什么选择?

java - 如何获取图像的路径?

arrays - 在 Matlab 中有效地存储 moSTLy 零的 N 维数组

Python - 如何保存/加载特定的cookie?

c# - UWP 将文件保存在文档和图片库中