Animated plots MATLAB [closed]

怎甘沉沦 提交于 2019-12-04 06:50:42

问题


I have problem to produce animated plots, using MATLAB.

I want to plot my signal y as a function of my time x (that i keep in two separate variables) and then produce an animation of it, seeing variations of my signal according to time.

At the end, I would like to produce both a succession of ".tif" images (for reading it in imageJ) and a ".avi" movie file.

It will really help me if someone can show me the way, because i try to do it by myself using MATLAB Help and forums, but i failed every time.

Thanks in advance!


回答1:


The standard way of doing this would be to update your plot data within a loop, and use getframe or a similar function to grab the current screen and save it to a file with imwrite or VideoWriter.

imwrite

With imwrite it is important that if you want to write multi-frame data (for either a TIFF or GIF) you want to use the 'WriteMode' parameter and set it to 'append' so that you simply add the new frame to the image. On the first time through the loop you don't want to append since that would append to an existing image that may already exist.

getframe

As far as getframe, it grabs a screenshot of the specified figure and returns a struct containing a colormap and the RGB image as cdata. This is the thing that you want to write to either your video or your multi-frame image.

VideoWriter

For writing to video, you'll use the VideoWriter class which behaves a little differently. The main steps are:

  1. Create the object

    vid = VideoWriter('filename.avi');

  2. Open the object

    vid.open() % or open(vid)

  3. Write some data using writeVideo

    vid.writeVideo(data)

  4. Close the Video

    vid.close()

Then you can call writeVideo as many times as you want and each time it will add an additional frame.

Summary

Here is a demo which brings all of that together and writes a multi-frame TIFF as well as an AVI.

% Example data to plot
x = linspace(0, 2*pi, 100);
y = sin(x);


% Set up the graphics objects
fig = figure('Color', 'w');
hax = axes();
p = plot(NaN, NaN, 'r', 'Parent', hax, 'LineWidth', 2);
set(hax, 'xlim', [0, 2*pi], 'ylim', [-1 1], 'FontSize', 15, 'LineWidth', 2);

% Create a video object
vid = VideoWriter('video.avi')
vid.open()

% Place to store the tiff
tifname = 'image.tif';

for k = 1:numel(x)
    set(p, 'XData', x(1:k), 'YData', y(1:k));

    % Grab the current screen
    imdata = getframe(fig);

    % Save the screen grab to a multi-frame tiff (using append!)
    if k > 1
        imwrite(imdata.cdata, tifname, 'WriteMode', 'append')
    else
        imwrite(imdata.cdata, tifname);
    end

    % Also write to an AVI
    vid.writeVideo(imdata.cdata);
end

% Close the video
vid.close()

Results (as an animated GIF)



来源:https://stackoverflow.com/questions/34949843/animated-plots-matlab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!