Product Support
1204 - Movie and Animation Guide
Introduction
MATLAB Functions for Movies
Resolutions for Movies
- How Do I Create an AVI Movie Without Displaying My Figure?
- How Do I Generate Higher Resolution AVI Files?
- How Do I Play a Movie Backwards? Can I Control the Order the Frames Are Played?
- How Much Memory Does the Movie Require?
- Can I Play Sound with the Movie?
Troubleshooting For Movies
- Why Do I Get Errors When Using ADDFRAME to Add Frames to the AVI File?
- When I Move My Movie Around While It Is Generating, Why Do I Receive Errors?
- Why Does Deleting A Movie File That I Created With AVIFILE Cause MATLAB to Crash?
- Why Do I Get the Error "Failed To Open File"?
- Why Does the Movie Pause When It Is Played?
- Why Are the Limits And Labels Wrong While Making a Movie?
- What Should I Do If None of the Troubleshooting Suggestions Resolve My Problem?
Other Interests
MATLAB Properties For Animations
Resolutions For Animations
- How Do I Eliminate Flickering in an Animation?
- How Do I Leave A Trail Behind in an Animation?
- How Do I Manage the Color of the Object in an Animation?
- How Do I Avoid Damaging the Images Behind the Object in an Animation?
- How Do I Increase the Speed of an Animation?
- What Should I Do If None of the Troubleshooting Suggestions Resolve My Problem?
Introduction
Section 1: What Is the Purpose of This Document?
MATLAB provides three functions for generating movies: AVIFILE , GETFRAME , and MOVIE. This technical note will demonstrate how you can use MATLAB to generate audio video interleaved (AVI) files. It will explain which MATLAB functions are needed to create and manipulate AVI files.
Note: Animation is not the same thing as playing a movie. MOVIE is a command that plays pre-recorded information. Animation is the process of continuously drawing and/or changing an object. Animation is used in the Lorenz Attractor demo. In case you are not familiar with this demo, it shows an object that is continuously moving. In order to view this demo, type
lorenzat the MATLAB command prompt. The trick behind animation in MATLAB is the EraseMode property. Before creating movies and animations, you must first understand what each command does and how the commands work.
You do not need extra toolboxes to create AVI files.
MATLAB Functions for Movies
Section 2: AVIFILE
Purpose:Creates a new audio video interleaved (AVI) file
Syntax:aviobj = avifile(filename) aviobj = avifile(filename,'PropertyName',value,...)Description:
aviobj = avifile(filename) creates an AVI file, giving it the name specified in filename, using default values for all AVI file object properties. If filename does not include an extension, avifile appends .avi to the filename. AVI is a file format for storing audio and video data. AVIFILE returns a handle to an AVI file object, aviobj. You can use this object to refer to the AVI file in other functions. An AVI file object supports properties and methods that control aspects of the AVI file created.
aviobj = avifile(filename,'Param',Value,'Param',Value,...) creates an AVI file with the specified parameter settings. For more information on the available parameters, see the documentation.
Section 3: AVIINFO
Purpose:Access information about an audio video interleaved (AVI) file
Syntax:
fileinfo = aviinfo(filename)Description:
fileinfo = aviinfo(filename) returns a structure whose fields contain information about the AVI file specified in the string, filename. If filename does not include an extension, then .avi is used. The file must be in the current working directory or in a directory on the MATLAB path. For more information on the set of fields in the fileinfo structure, visit the documentation.
Section 4: AVIREAD
Purpose:Read an Audio Video Interleaved (AVI) file.
Syntax:fmov = aviread(filename) fmov = aviread(filename,index)Description:
fmov = aviread(filename) reads the AVI movie filename into the MATLAB movie structure mov. If filename does not include an extension, then .avi is used. Use the MOVIE function to view the movie, which is named fmov in the above syntax. On UNIX, filename must be an uncompressed AVI file.
fmov has two fields, cdata and colormap. The content of these fields varies depending on the type of image.
| Image Type | mov.cdata Field | mov.colormap Field |
| Truecolor | height-by-width-by-3 array | Empty |
| Indexed | height-by-width array | m-by-3 array |
fmov = aviread(filename,index) reads only the frame(s) specified by index. index can be a single index or an array of indices into the video stream. In AVI files, the first frame has the index value 1, the second frame has the index value 2, and so on. For more information, see the documentation.
Section 5: GETFRAME
Purpose:Access a movie frame. (The frame is a snapshot, or pixmap, of the current axes or figure.)
Syntax:F = getframe F = getframe(h) F = getframe(h,rect) [X,Map] = getframe(...)Description:
F = getframe gets a frame from the current axes.
F = getframe(h) gets a frame from the figure or axes identified by the handle h.
F = getframe(h,rect) specifies a rectangular area from which to copy the pixmap. rect is relative to the lower-left corner of the figure or axes h , in pixel units. rect is a four-element vector in the form [left bottom width height] , where width and height define the dimensions of the rectangle.
F = getframe(...) returns a movie frame, which is a structure having two fields:
- cdata : The image data stored as a matrix of uint8 values. The dimensions of F.cdata are height-by-width-by-3.
- colormap : The colormap stored as an n-by-3 matrix of doubles. F.colormap is empty on true color systems.
[X,Map] = getframe(...) returns the frame as an indexed image matrix X and a colormap Map. This version is obsolete and is supported only for compatibility with earlier version of MATLAB. Since indexed images cannot always capture true color displays, you should use the single output argument form of GETFRAME to write code that is compatible with earlier versions of MATLAB and that can take advantage of true color support. For more information, see the documentation.
Section 6: ADDFRAME
Purpose:Adds a frame to an audio video interleaved (AVI) file.
Syntax:aviobj = addframe(aviobj,frame) aviobj = addframe(aviobj,frame1,frame2,frame3,...) aviobj = addframe(aviobj,mov) aviobj = addframe(aviobj,h)Description:
aviobj = addframe(aviobj,frame) appends the data in the frame to the AVI file identified by aviobj , which was created by a previous call to AVIFILE. frame can be either an indexed image (m-by-n) or a truecolor image (m-by-n-by-3) of double or uint8 precision. If frame is not the first frame added to the AVI file, it must be consistent with the dimensions of the previous frames.
ADDFRAME returns a handle to the updated AVI file object, aviobj. For example, ADDFRAME updates the TotalFrames property of the AVI file object each time it adds a frame to the AVI file.
aviobj = addframe(aviobj,frame1,frame2,frame3,...) adds multiple frames to an AVI file.
aviobj = addframe(aviobj,mov) appends the frame(s) that are contained in the MATLAB movie, mov , to the AVI file, aviobj. MATLAB movies that store frames as indexed images use the colormap in the first frame as the colormap for the AVI file, unless the colormap has been previously set.
aviobj = addframe(aviobj,h) captures a frame from the figure or axis handle h , and appends this frame to the AVI file. ADDFRAME renders the figure into an offscreen array before appending it to the AVI file. This ensures that the figure is written correctly to the AVI file even if the figure is obscured on the screen by another window or screen saver. For more information, see the documentation.
Section 7: CLOSE
Purpose:Finish writing and close AVI file
Syntax:aviobj = close(aviobj)Description:
aviobj = close(aviobj) finishes writing and closes the AVI file associated with aviobj, which is an AVIFILE object obtained from AVIFILE. For more information, see the documentation.
Section 8: MOVIE
Purpose:Play recorded MATLAB movie frames
Syntax:movie(M) movie(M,n) movie(M,n,fps) movie(h,...) movie(h,M,n,fps,loc)Description:
movie plays the movie defined by a matrix whose columns are movie frames (usually produced by getframe).
movie(M) plays the movie in matrix M once.
movie(M,n) plays the movie n times. If n is negative, each cycle is shown forward and then backward. If n is a vector, the first element is the number of times to play the movie, and the remaining elements comprise a list of frames to play in the movie. For example, if M has four frames, then n = [10 4 4 2 1] plays the movie ten times, and the movie consists of frame 4 followed by frame 4 again, followed by frame 2 and finally frame 1.
movie(M,n,fps) plays the movie at fps frames per second. The default is 12 frames per second. Computers that cannot achieve the specified speed play as fast as possible.
movie(h,...) plays the movie in the figure or axes identified by the handle h.
movie(h,M,n,fps,loc) specifies a four-element location vector, [x y 0 0] , where the lower-left corner of the movie frame is anchored (only the first two elements in the vector are used). The location is relative to the lower-left corner of the figure or axes specified by handle and in units of pixels, regardless of the object's Units property. For more information, see the documentation.
Section 9: MOVIE2AVI
Purpose:Creates an audio video interleaved (AVI) movie from a MATLAB movie
Syntax:movie2avi(mov,filename) movie2avi(mov,filename,param,value,param,value...)Description:
movie2avi(mov,filename) creates the AVI movie filename from the MATLAB movie mov.
movie2avi(mov,filename,param,value,param,value...) creates the AVI movie filename from the MATLAB movie mov using the specified parameter settings. For more information, see the documentation.
Resolutions for Movies
Section 10: How Do I Create an AVI Movie Without Displaying My Figure?
To avoid this display effect, pass the figure or axes handle directly to ADDFRAME.You may also turn visibility of the figure OFF so that you can run your code without having the figure displayed.
Note: You can pass the figure or axes handles to ADDFRAME directly only if the graphics in the animation are not using XOR graphics.
The following example demonstrates this:
aviobj=avifile('test.avi'); %creates AVI file, test.avi
hf= figure('visible','off'); %turns visibility of figure off
hax=axes;
for k=1:10
image(k.*peaks,'parent',hax); %puts image in invisible axes
set(gca,'Zlim',[-20 20]);
aviobj=addframe(aviobj,hf); %adds frames to the AVI file
end
aviobj=close(aviobj); %closes the AVI file
close(hf); %closes the handle to invisible figure
Section 11: How Do I Generate Higher Resolution AVI Files?
To generate higher resolution AVI files, you need to change the compression being used. Indeo 3 is the default codec but Indeo 5 is known to be more robust. In order to further increase the resolution of your movie, you should maximize the size of the figure window. This is demonstrated in the following example. Setting the compression to none results in the highest resolution, but this is at the expense of the file size.
The following example demonstrates how you can get the maximum resolution for the movie.
figure('units','normalized','outerposition',[0 0 1 1]);
% outerposition is an undocumented feature. It allows you to
% define the size of the outerposition of the figure window.
% The above sets the figure to full screen or you could also
% try uncommenting the statements after the surf(peaks)
surf(peaks);
%disp ('Maximize the screen, then press any key to continue');
%pause;
mov=avifile('test','compression','indeo5');
%makes test.avi w/ Indeo 5
f2=getframe(gcf); % gets the gcf
mov=addframe(mov,f2); % adds the frame into mov
mov=close(mov); % closes the mov
%In order to run the avi from MATLAB command window:
!test.avi&
The following pictures show the difference in resolutions:
Low Resolution (using indeo3)
High Resolution (using indeo5)
Highest resolution (using indeo5 with full screen)
Section 12: How Do I Play a Movie Backwards? Can I Control the Order the Frames Are Played?
N controls the number of times a movie is played, as well as the order of frames. To play a movie N times forward and N times backwards, use -N in the movie command. To specify the order of the frames, specify a vector of integer values for N. The first element is the number of times the movie is played, and the remaining elements correspond to the frames. For example, if a movie consists of five frames, to play it once backwards, set N = [1 5 4 3 2 1].
Section 13: How Much Memory Does the Movie Require?
GETFRAME creates a huge vector for each frame. The size of the vector created by getframe is independent of the data in the axes/figure. Remember, GETFRAME is creating a pixel-by-pixel map of the area. Since this is the case, the size of the vector is dependent only on the size of the area recorded. The larger the area, the greater the number of recorded pixels, and the larger the vector.
On X machines, the X server must have enough memory to load all the frames at once. One of the most common problems people have with MATLAB movies is that they run out of memory and do not know why.
On PCs and MACs, you need approximately twice the amount of memory as the MATLAB movie data in order to play the movie. For example, if M is 2Mb, then you need at least 4Mb to play the MATLAB movie.
You can save memory by creating AVI movies rather than MATLAB movies. While generating AVI movies, you need to create a frame at a time. Therefore, this saves more space than MATLAB movie files.
Section 14: Can I Play Sound with the Movie?
You cannot play sound at the same time movies are played.
Troubleshooting for Movies
Section 15: Why do I get the following errors when using ADDFRAME to add frames to the AVI File?
Can not locate compressor.Not enough memory available for compressor.
Compressor can not compress this data type.
Failed to make compressed stream. Unable to determine reason.
Failed to set stream format.
Failed to write stream data.
If you receive any of these errors, try using a different codec (compressor/decompressor). Indeo 3 is the default codec, but Indeo 5 is known to be more robust. The following example demonstrates this:
% makes test.avi with Indeo 5
aviobj=avifile('test','compression','indeo5');
Section 16: When I Move My Movie Around While It Is Generating, Why Do I Receive Errors?
Why is it that when I move my movie around while it is generating, it gives me the following error?
??? Error using ==>avifile/addframe (ValidateFrame)Frame must be 560 by 420.
Error in ==>D:\Applications\matlabr12\toolbox\matlab\iofun\@avifile\addframe.m
On line 167==>ValidateFrame(aviobj,width, height,dims);
This error occurs if you move the figure off the screen. If you move the figure around and keep the entire figure visible within the screen, the error will not occur. You can also get this error if your axes changes sizes when using GETFRAME , which can occur if you are rotating your figure. You can prevent this behavior by using the command GETFRAME(GCF ) instead of just GETFRAME to capture the movie frame. This is due to the function GETFRAME. GETFRAME takes a screen capture of the figure, and if the figure is off the screen, it captures the visible part of the figure. Since this one image is smaller than the other frames, MATLAB will produce an error.
Section 17: Why Does Deleting A Movie File That I Created With AVIFILE Cause MATLAB to Crash?
When I use the following command to save to an AVI file,
avifile(moviename,'QUALITY',... 70,'FPS',10,'COMPRESSION','MSVC','KEYFRAME',1)
I get a sharing violation if I try to delete it. I have to exit MATLAB to delete the file. This behavior is expected. AVIFILE creates a handle to an avi file and leaves that file open so that calls to ADDFRAME can write to the file. If the file is not closed, you will get sharing violations when trying to access it. You should use CLOSE (overloaded for AVIFILE objects) to close the file and release the handle. A situation may occur when the handle to the AVI file is "lost" before CLOSE is called (i.e., error inside the M-file, overwrite the handle variable, etc). In this case, use
clear mex
or
clear allto close the avifile. Note: Using fclose('all') does NOT close files opened by AVIFILE.
Section 18: Why do I get the error "Failed to open file"?
??? Failed to open file. Error in ==>D:\Applications\MATLABR12p1\toolbox\matlab\iofun\@avifile\private\avi.dllError in ==>D:\Applications\MATLABR12p1\toolbox\matlab\iofun\@avifile\avifile.m
On line 162 ==>aviobj.FileHandle = avi('open',filename);
Error in ==>D:\Applications\MATLABR12p1\toolbox\matlab\iofun\movie2avi.m
On line 66 ==>avimov = avifile(filename,varargin{:});
The handle to the AVI file was "lost" before CLOSE is called (i.e., error inside the M-file, overwrite the handle variable, etc). In this case, use
clear mex
or
clear allto close the avifile. It is also possible that the permissions for the AVI file are read only. Try changing the permissions so that you have write permissions as well.
Section 19: Why Does the Movie Pause When It Is Played?
There are several reasons why a movie may pause when it is played. First, since movies are very memory intensive, it may be necessary to swap information in and out of memory to play the movie. The second reason is the load on the network or CPU. If someone logs onto your machine, this may cause a momentary delay in the playback, and if the load is very high on the network, then communication between the client and XServer will be affected.
Section 20: Why Are the Limits And Labels Wrong While Making a Movie?
The method you choose depends on the information that you wish to record and where you wish to play the movie. This will record the events occurring within the current axes, however, but not the axes limits and labels. When the movie is played using movie(M) , it is played in the current axes. If there is not an axis, then one will be created. Below is an example of this method.
figure for x = 1:5 plot(sin(x*pi*[0:0.025:2])) M(:,x) = getframe; end movie(M)
After running this example, you will notice that the axes limits do not correspond to the plot. This is because the movie was recorded with respect to the box that defines the axes. Everything outside the box is not recorded. When the movie is played, it creates an axis and uses it as a point of reference only. The default limits of an axis are 0 and 1.
The most useful and practical way to use GETFRAME and MOVIE is to record the events with respect to the figure, and to record the entire contents of the figure. By doing this, every change that occurs in the figure will be recorded. This means that axes limits and labels get recorded as well as multiple plots. For example,
%Define the area to be recorded hf=figure; rect = get(hf,'Position'); rect(1:2) = [0 0];
% Generate and record the frames for x = 1:5 t = 0:pi/10:x*pi; subplot(2,1,1) plot(t,sin(t)) axis([0 5*pi -1 1]) subplot(2,1,2) plot(t,cos(t)) axis([0 5 -1 1]) M(:,x) = getframe(hf,rect); end
% Play the MATLAB movie clf N = 1; FPS = 10; movie(hf,M,N,FPS,rect)
The first two lines in this example are used to create the rectangle that is used by GETFRAME. This vector uses the same format as position vectors. Therefore, the easiest way to define a rectangle that is the entire figure is to reference the figure's position. Since the first two elements of the figure's position vector are the X and Y coordinates of the figure with respect to the lower-left corner of the screen, they are zeroed out, so that the first two elements are relative to the lower-left corner of the figure. The third and fourth values define the width and height.
Since the frames are recorded with respect to the figure, it makes sense that the movie should be played with respect to the figure. To play a movie with respect to a figure, you should use all five inputs for the movie, specifying the handle to a figure in the first input. If you do not, the movie will be played in the current axes. As stated above, N is the number of times the movie is played, and FPS is the number of frames played per second.
Section 21: What Should I Do If None of the Troubleshooting Suggestions Resolve My Problem?
If you continue to experience problems with AVI files or if this Technical Note did not address your issue, send the following information to
- The output of typing VER at the MATLAB command prompt
- A detailed description of the problem
- A small example (5 - 10 lines of code)
- Step-by-step instructions so that we can try to reproduce the problem
- The exact error message(s), if any
Other Interests
Section 22: How Do I Create MPEG Files From MATLAB Movies And Vice-Versa?
There are two functions called MPGWRITE and MPGREAD for creating MPEG files on UNIX and PC platforms. MPGWRITE translates a MATLAB movie into an MPEG file. MPGREAD translates a movie file in MPEG format into a MATLAB movie matrix.
You can obtain these files below:
Note: The previous files have not been fully tested by The Mathworks. The MathWorks therefore does not guarantee or warrant the use or content of those submissions.
MATLAB Properties for Animations
Section 23: Erase Mode
The EraseMode property controls how and when the object is drawn and deleted. By default, when an object is added or changed, new objects or changes are not drawn until the axes are refreshed. This occurs instantly from the command line, however, in M-files the axes are not updated until a DRAWNOW , GETFRAME , or PAUSE statement is executed, or return to the command prompt is given. When the axes are updated, every object is also updated. This means that they are redrawn. Not all objects have an EraseMode property, only lines, patches, surfaces, and text.
Section 24: NORMAL
When EraseMode is set to normal , the default, the axes will control when the object is updated. This means that the axes will flicker when an object is drawn, changed, or deleted.
Section 25: BACKGROUND
When EraseMode is set to background , the object deletes its graphics by drawing itself in the figure's background color. The major disadvantage with this method is that objects behind this object are damaged.
Section 26: XOR
When EraseMode is set to xor , the object is drawn and erased by xor'ing it with the color beneath it. When the object is erased, objects behind it are not damaged.
Section 27: NONE
When EraseMode is set to none , the object is not erased when it is moved or destroyed.
Section 28: Backing Store
Another property which influences animation is BackingStore. BackingStore is a property of figure and is used to fill in areas quickly that were covered by other windows.
Section 29: ON
When BackingStore is set to On , the default, two copies of each figure are made. One is displayed in the figure window, and the other is used to patch areas that were previously covered. The advantage of setting the BackingStore property to On is that the entire figure window does not have to be updated to fill in a region that was covered by another window. The disadvantage is that setting BackingStore to On forces MATLAB to use additional resources.
Section 30: OFF
By setting BackingStore to Off , only one copy is made, thus reducing the amount of work required to create the plot. The advantage of setting the BackingStore property to Off is that it reduces the resources required to produce a plot. The major disadvantage is that the entire figure window must be refreshed to fill in areas that were covered by other windows.
Resolutions for Animations
Section 31: How Do I Eliminate Flickering in an Animation?
If you want to eliminate flickering, you should not use normal as the EraseMode. For more information, see the section on EraseMode.
As of MATLAB 5.2 (R10), you can use the DoubleBuffer property. This property controls whether the erasing and redrawing of a rendering occurs on-screen (the default setting) or off-screen (the optional setting). This is useful because it can prevent the "flashing" you might see during animations. Its disadvantage is that the graphics display may take more time (but it shouldn't take more memory since BackingStore information is used). You can change the DoubleBuffer property through SET. For example:
get(gcf,'DoubleBuffer') % To query the property set(gcf,'DoubleBuffer','on') % To turn it on set(gcf,'DoubleBuffer','off') % To turn it off (the default)
For example:
figure h=patch([0 1 0 1],[0 1 1 0],'r'); hold on h1=plot(linspace(0,1,100),linspace(0,1,100),'b'); tic for i=1:100 set(h1,'Ydata',rand(1,100)); drawnow end Elapsed_Time=toc
% Compare the above to the same example, % but with 'DoubleBuffer' set to 'On' : figure set(gcf,'DoubleBuffer','on'); h=patch([0 1 0 1],[0 1 1 0],'r'); hold on h1=plot(linspace(0,1,100),linspace(0,1,100),'b'); tic for i=1:100 set(h1,'Ydata',rand(1,100)); drawnow end Elapsed_Time=toc
For more information on DoubleBuffer, see the documentation.
Section 32: How Do I Leave A Trail Behind in an Animation?
If you want to see a trail left behind, as in the Lorenz Attractor demo, then use none as the EraseMode .For more information, see the section on EraseMode .
Section 33: How Do I Manage the Color of the Object in an Animation?
If you are concerned about the color of the object and do not care what happens to objects beneath it, then use background as the EraseMode. For more information, see the section on EraseMode .
Section 34: How Do I Avoid Damaging the Images Behind the Object in an Animation?
If you do not want to damage objects that are beneath the object, then use xor as the EraseMode. For more information, see the section on EraseMode .
Section 35: How do I increase the speed of an animation?
As stated above, the benefit of using EraseMode is that you can control how and when objects are drawn and deleted. By using any setting other than normal , you can greatly increase the speed of the animation. Try the following two programs to verify this:
%Program 1: EraseMode set to normal figure h = plot(1:100,.01:.01:1) axis([0 100 0 1]) tic for x = 1:100 set(h,'YData',rand(1,100)) drawnow end toc %Program 2: 'EraseMode' set to xor figure h = plot(1:100,.01:.01:1,'EraseMode','xor') axis([0 100 0 1]) tic for x = 1:100 set(h,'YData',rand(1,100)) drawnow % drawnow is needed only under MS-Windows end toc
As you can see, the setting of EraseMode can greatly influence the speed of the program. When the EraseMode is set to something other than normal , the axes and other objects are not redrawn. This saves a lot of time and makes the animation run smoothly.
In addition to animation, the EraseMode property can be used to add lines, patches, surfaces, and text to plots without causing the plot to redraw. For example:
plot(1:10) text(1,1,'Flickers') text(5,5,'No Flicker','EraseMode','Xor')
The first text object will cause the screen to update, the second will not.
Section 36: What Should I Do If None of the Troubleshooting Suggestions Resolve My Problem?
If you continue to experience problems with AVI files, send the following information to support@mathworks.com:
- The output of typing VER at the MATLAB command prompt
- A detailed description of the problem
- A small example (5 - 10 lines of code)
- Step-by-step instructions so that we can try to reproduce the problem
- The exact error message(s), if any
Store