MATLAB制作绘图动画/保存视频

 


           MATLAB制作绘图动画/保存视频

命令有哪些:coment    二维彗星图  https://ww2.mathworks.cn/help/matlab/ref/comet.html?s_tid=srchtitle

                     coment3  三维彗星图  https://ww2.mathworks.cn/help/matlab/ref/comet3.html?s_tid=srchtitle

                     scattter    二维散点图   https://ww2.mathworks.cn/help/matlab/ref/scatter.html?s_tid=srchtitle      

                     scattter3   三维散点图   https://ww2.mathworks.cn/help/matlab/ref/scatter3.html?s_tid=srchtitle   

                     animatedline   创建动画线条    https://ww2.mathworks.cn/help/matlab/ref/animatedline.html

 好文参考:https://blog.csdn.net/zengxiantao1994/article/details/77482852   --比较全面

 

    getframe函数和movie函数详解:getframe函数可以捕捉动画帧,并保存到矩阵中。该函数的主要格式有:

        1、f = getframe,从当前图形框中得到动画帧;

        2、f = getframe(h),从图形句柄h中得到动画帧;

        3、f = getframe(h,rect),从图形句柄h的指定区域rect中得到动画帧。

        当创建了一系列动画帧后,可利用movie函数播放这些动画帧。该函数的主要格式有:

        1、movie(M),将矩阵M中的动画帧播放一次;

        2、movie(M, n),将矩阵M中的动画帧播放n次

        3、movie(M, n, fps),将矩阵M中的动画帧以每秒fps帧的速度播放n次。

             axis square 当前坐标系图形设置为方形,刻度范围不一定一样,但是一定是方形的。

             axis equal 将横轴纵轴的定标系数设成相同值,即单位长度相同,刻度是等长的,但不一定是方形的。

            axis manual:将坐标轴的范围锁定为当前范围。如果打开了hold on命令,则后续的图形都使用同样的坐标范围。该函数设置XLimMode、YLimMode和ZLimMode属性为manual值。

一.使用 animatedline 

参考:https://ww2.mathworks.cn/help/matlab/ref/animatedline.html

an = animatedline 创建一根没有任何数据的动画线条并将其添加到当前坐标区中。通过使用 addpoints 函数循环向线条中添加点来创建动画。

an = animatedline(x,y) 创建一根包含由 x 和 y 定义的初始数据点的动画线条。

an = animatedline(x,y,z) 创建一根包含由 xy 和 z 定义的初始数据点的动画线条。

an = animatedline(___,Name,value) 使用一个或多个名称-值对组参数指定动画线条属性。例如,'Color','r' 将线条颜色设置为红色。在前面语法中的任何输入参数组合后使用此选项。

an = animatedline(ax,___) 将在由 ax 指定的坐标区或地理坐标区中,而不是在当前坐标区 (gca) 中创建线条。选项 ax 可以位于前面的语法中的任何输入参数组合之前。

1
2
3
4
5
6
7
8
9
10
11
12
clc;close all;clear;
 
%%
x = 0:0.05:8*pi;
y = sin(x);
figure(1)
curve = animatedline('color','r','linestyle','-.','linewidth',2,'marker','o');%指定线条特性set(gca,'XLim',[0,8*pi],'YLim',[-1,1]);
grid on
legend('Anmiated Sine')
for i =1:length(x)
    addpoints(curve,x(i),y(i))<br>    drawnow
end

 

加快动画绘制速度的方法:

1
1.使用命令:drawnow limitrate  2.每次添加点数增多例1:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
clc;close all;clear;
 
%%
x = 0:0.05:8*pi;
y = sin(x);
figure(1)
curve = animatedline('color','r','linestyle','-.','linewidth',2,'marker','o');%指定线条特性
set(gca,'XLim',[0,8*pi],'YLim',[-1,1]);
grid on
legend('Anmiated Sine')
for i =1:length(x)
    addpoints(curve,x(i),y(i))
    %drawnow
    drawnow limitrate %the command ‘limitrate' is used to speed up the plot speed<br>    %pause(0.001)  %每执行一次命令就暂停0.001s<br>end

  

例2:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
clc;close all;clear;
 
%%
x = 0:0.05:8*pi;
y = sin(x);
figure(1)
curve = animatedline('color','r','linestyle','-.','linewidth',2,'marker','o');
set(gca,'XLim',[0,8*pi],'YLim',[-1,1]);
grid on
legend('Anmiated Sine')
for k =1:11:length(x)-10
    xvec = x(k:k+10);%一次多添加几个点
    yvec = y(k:k+10);
    addpoints(curve,xvec,yvec)
    drawnow
end 

 

 

控制动画速度

1
2
3
4
5
drawnow
drawnow limitrate
tic
toc
b > (1/1000)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
clc;close all;clear;
 
%%
x = 0:0.05:8*pi;
y = sin(x);
figure(1)
curve = animatedline('color','r','linestyle','-.','linewidth',2,'marker','o');%指定线条特性
set(gca,'XLim',[0,8*pi],'YLim',[-1,1]);
grid on
legend('Anmiated Sine')
for i =1:length(x)
    addpoints(curve,x(i),y(i))
    pause(0.001)  %每执行一次命令就暂停0.001s
end

  

1
<br>例2:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
h = animatedline;
axis([0,4*pi,-1,1])
numpoints = 10000;
x = linspace(0,4*pi,numpoints);
y = sin(x);
a = tic; % start timer
for k = 1:numpoints
    addpoints(h,x(k),y(k))
    b = toc(a); % check timer
    if b > (1/30)
        drawnow % update screen every 1/30 seconds
        a = tic; % reset timer after updating
    end
end
drawnow % draw final frame

 

动画演示标记沿着线条移动。

https://ww2.mathworks.cn/help/matlab/creating_plots/trace-marker-along-line.html

使用scatter也可以实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
%动画演示标记沿着线条移动。
figure
x = linspace(0,10,1000);
y = sin(x);
plot(x,y)
hold on
p = plot(x(1),y(1),'o','MarkerFaceColor','red');
hold off
axis manual
 
for k = 2:length(x)
    p.XData = x(k);
    p.YData = y(k);
    drawnow
end

  

  

三维的绘图效果

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
z = 0:0.05:10;
y = sin(2*z);
x = cos(2*z);
figure(2)
curve = animatedline('linewidth',3,'color','b');
set(gca,'XLim',[-1.5,1.5],'YLim',[-1.5,1.5],'ZLim',[0 10]);
grid on
hold on
view(43,24); % viewpiont
for i =1:length(z)
    addpoints(curve,x(i),y(i),z(i))
    head =scatter3(x(i),y(i),z(i),'filled','MarkerFaceColor','g','MarkerEdgeColor','r');
    drawnow
  % pause(0.01)  %reduce the plotspeed
  % delete(head);
end

 

 

加上delete head 的效果 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
z = 0:0.05:10;
y = sin(2*z);
x = cos(2*z);
figure(2)
curve = animatedline('linewidth',3,'color','b');
set(gca,'XLim',[-1.5,1.5],'YLim',[-1.5,1.5],'ZLim',[0 10]);
grid on
hold on
view(43,24); % viewpiont
for i =1:length(z)
    addpoints(curve,x(i),y(i),z(i))
    head =scatter3(x(i),y(i),z(i),'filled','MarkerFaceColor','g','MarkerEdgeColor','r');
    drawnow
   %pause(0.01)  %reduce the plotspeed
    delete(head);
end

 

 

二 .创建视频动画 

命令:VideoWriter       详细的视频属性参考:https://ww2.mathworks.cn/help/matlab/ref/videowriter.html#d122e1351518

   v = VideoWriter(filename) 创建一个 VideoWriter 对象以将视频数据写入采用 Motion JPEG 压缩技术的 AVI 文件。

   v = VideoWriter(filename,profile) 还应用一组适合特定文件格式(例如 'MPEG-4' 或 'Uncompressed AVI')的属性。

   filename文件名;profile文件类型,默认为‘Motion JPEG AVI’

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
%% creating a video
 
z = 0:0.05:10;
y = sin(2*z);
x = cos(2*z);
figure(3)
curve = animatedline('linewidth',2,'color','b');
set(gca,'XLim',[-1.5,1.5],'YLim',[-1.5,1.5],'ZLim',[0 10]);
grid on
hold on
view(43,24); % viewpiont
% title('Melix');
% set(gcf,'Units','normalized','OuterPosition',[0 0 1 1]); % 使用更大的页面看图 ,set(gcf) 获的图片
for i =1:length(z)
    addpoints(curve,x(i),y(i),z(i))
    head =scatter3(x(i),y(i),z(i),'MarkerFaceColor','b','MarkerEdgeColor','r');
    % head =scatter3(x(i),y(i),z(i),'filled','MarkerFaceColor','b','MarkerEdgeColor','r');
    drawnow
    F(i) = getframe(gcf);
    % pause(0.01)  %reduce the plotspeed
    delete(head);
    title(['t = ',num2str(i)])
end
 
video = VideoWriter('helix.avi','Uncompressed AVI'); % 可以选'Uncompressed AVI', 或者内存更小的 'MPEG-4'也就是MP4
video.FrameRate = 60; %视频帧数<br>video.Quality = 90;   %视频质量,默认75,取值[0,100]
open(video)
writeVideo(video,F);
close(video)

  

 

不随时间旋转的情况,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
%% Step 1: Generate Data
%Animate a point moving along a 3D parametric curve
t = linspace(0,2*pi,100);
x = 5*cos(t);
y = 2*sin(t);
z = t;
 
%% Step 2: Draw/Render Scenario
figure;
for k=1:length(t)
    %Clear the figure to start with a blank slate
    clf %clean the figure marker everytime
     
    %Extract data at the current time step
    t_k = t(k);
    x_k = x(k);
    y_k = y(k);
    z_k = z(k);
     
    %Where is the current point?
    plot3(x_k, y_k, z_k, 'go', 'LineWidth', 3, 'MarkerSize', 15)
     
    %Plot the entire curve
    hold on
    plot3(x, y, z, 'b-', 'LineWidth', 2);
     
    %Add plotting options
    grid on
    xlabel('x')
    ylabel('y')
    zlabel('z')
    title(['t = ',num2str(t_k)])
    view([30 35])     
    %% Step 3: Take a Snapshot
    %   force Matlab to Draw the image at this point
%   drawnow
%   pause(0.01)
    %Save the frame
    movieVector(k) = getframe;
     
 
    %% Step 4: Advance Time
    %Happens automatically if using a for loop
end
 
%% Step 5: Save Movie
%Create a VideoWriter object and set properties
myWriter = VideoWriter('curve');              %create an .avi file
% myWriter = VideoWriter('curve','MPEG-4');   %create an .mp4 file
myWriter.FrameRate = 20;
 
%Open the VideoWriter object, write the movie, and close the file
open(myWriter);
writeVideo(myWriter, movieVector);
close(myWriter);
disp('DONE!') 

 

随时间旋转

要对getframe的捕获图形区域进行限制,否则会出现随着时间发生变话,每张图获得的帧数不一致,为此加了这一行

figh = figure;

 movieVector(k) = getframe(figh, [10 10 520 400]);   %manually specify getframe region

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
%Christopher Lum
%lum@uw.edu 
%Illustrate animation in Matlab
%This file is designed to accompany the YouTube video at https://youtu.be/3I1_5M7Okqo
 
clear
clc
close all
 
%% Step 1: Generate Data
%Animate a point moving along a 3D parametric curve
t = linspace(0,2*pi,100);
x = 5*cos(t);
y = 2*sin(t);
z = t;
 
%% Step 2: Draw/Render Scenario
figh = figure;
for k=1:length(t)
    %Clear the figure to start with a blank slate
    clf % clean the figure marker everytime
     
    %Extract data at the current time step
    t_k = t(k);
    x_k = x(k);
    y_k = y(k);
    z_k = z(k);
     
    %Where is the current point?
    plot3(x_k, y_k, z_k, 'go', 'LineWidth', 3, 'MarkerSize', 15)
     
    %Plot the entire curve
    hold on
    plot3(x, y, z, 'b-', 'LineWidth', 2);
     
    %Add plotting options
    grid on
    xlabel('x')
    ylabel('y')
    zlabel('z')
    title(['t = ',num2str(t_k)])
%     view([30 35])
   view([30+20*t_k 35])      %show how viewpoint can be manipulated
 
    %% Step 3: Take a Snapshot
    % force Matlab to Draw the image at this point
%   drawnow
%   pause(0.01)
    %Save the frame
%   movieVector(k) = getframe;
    movieVector(k) = getframe(figh, [10 10 520 400]);   %manually specify getframe region
 
    %% Step 4: Advance Time
    %Happens automatically if using a for loop
end
 
%% Step 5: Save Movie
%Create a VideoWriter object and set properties
myWriter = VideoWriter('curve');              %create an .avi file
% myWriter = VideoWriter('curve','MPEG-4');   %create an .mp4 file
myWriter.FrameRate = 20;
 
%Open the VideoWriter object, write the movie, and close the file
open(myWriter);
writeVideo(myWriter, movieVector);
close(myWriter);
 
disp('DONE!')

上述方法虽然可行,但对于大规模数据绘图来说较慢,因为他是每次重新绘图的

采用下面的方式可会绘制较快。

axes --用法参考:https://ww2.mathworks.cn/help/matlab/ref/matlab.graphics.axis.axes-properties.html

                            https://ww2.mathworks.cn/help/matlab/ref/axes.html?s_tid=srchtitle

                            https://www.cnblogs.com/stxs/p/8721348.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
%% 这个方法运行更快,因为只是每次刷新数据而已,不再每次重新画图
tic %计时
t = linspace(0,6*pi,100);
x = 5*cos(t);
y = 2*sin(t);
z = t;
figh =figure
ax = axes(figh,'XGrid','on','YGrid','on','Position',[0.1 0.1 0.8 0.8],'Box','on')
plot3(ax,x, y, z, 'b-', 'LineWidth', 2);           %plot the curve outside the loop only once
hold on
Plot1 = plot3(ax, 0, 0, 0,'go', 'LineWidth', 3, 'MarkerSize', 15);                           %initialize empty plot;
for k=1:length(t)
    
    %Extract data at the current time step
    t_k = t(k);
    x_k = x(k);
    y_k = y(k);
    z_k = z(k);
    Plot1.XData = x_k;  % refresh just the X Y Z data inside the loop (way quicker than reinitializing a whole new plot each time)
    Plot1.YData = y_k;
    Plot1.ZData = z_k;
    drawnow
end
toc

  

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
close all;clc;clear;
axis tight equal
%axis equal 沿每个坐标轴使用相同的数据单位长度
%axis tight 将坐标轴范围设置为等同于数据范围,使轴框紧密围绕数据
v = VideoWriter('exp3dVideo.avi'); %先创建一个空文件
open(v);
[x,y] = meshgrid(-10:0.5:10, -10:0.5:10);
r  = sqrt(x.^2+y.^2);
for k = 0:200
    z = cos(r/2+k/10).*exp(-r.^2/50);
    surf(x,y,z);
    xlim([-10,10]);
    ylim([-10,10]);
    zlim([-1,1]);
    frame = getframe(gcf);
    writeVideo(v,frame);
end
 
close(v);

  动态视频--但无法插入

 

 

三.创建GIF文件

命令:rgb2ind 将 RGB 图像转换为索引图像   https://ww2.mathworks.cn/help/matlab/ref/rgb2ind.html?s_tid=srchtitle

           imwrite 将图像写入图形文件                https://ww2.mathworks.cn/help/matlab/ref/imwrite.html?s_tid=srchtitle#btv3cny-5

           

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
z = 0:0.05:10;
y = sin(2*z);
x = cos(2*z);
figure(2)
curve = animatedline('linewidth',3,'color','b');
set(gca,'XLim',[-1.5,1.5],'YLim',[-1.5,1.5],'ZLim',[0 10]);
grid on
hold on
view(43,24); % viewpiont
for i =1:length(z)
    addpoints(curve,x(i),y(i),z(i))
    head =scatter3(x(i),y(i),z(i),'filled','MarkerFaceColor','g','MarkerEdgeColor','r');
    drawnow
  % pause(0.01)  %reduce the plotspeed
     
     %下面是用来画出GIF动画的
     frame = getframe;
     fm{i} = frame2im(frame);
     filename = 'test8_sin(x).gif'; %文件名称
    [A,map] = rgb2ind(fm{i},256);
    if i == 1
       imwrite(A,map,filename,'gif','LoopCount',Inf,'DelayTime',1);
    else
        imwrite(A,map,filename,'gif','WriteMode','append','DelayTime',1);
        delete(head);
    end
end

  

参考这个:没有这个语句,注意两个区别,并且用的是花括号引用的

1
fm{i} = frame2im(frame);

  

 前面画图的

 上述画GIF的代码:

  

 未完待续~~~

 没办法好像插入的视频,不显示哎!

 

 

posted @   试一下就知道了  阅读(6832)  评论(0编辑  收藏  举报
编辑推荐:
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
· PostgreSQL 和 SQL Server 在统计信息维护中的关键差异
· C++代码改造为UTF-8编码问题的总结
阅读排行:
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· 【.NET】调用本地 Deepseek 模型
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库
· 上周热点回顾(2.17-2.23)
· 如何使用 Uni-app 实现视频聊天(源码,支持安卓、iOS)
点击右上角即可分享
微信分享提示