问题
Matlab has the following guide to making a movie in avi format. My goal is to be able to play the video in my presentation through powerpoint.
nFrames = 20;
% Preallocate movie structure.
mov(1:nFrames) = struct('cdata', [],...
'colormap', []);
% Create movie.
Z = peaks; surf(Z);
axis tight
set(gca,'nextplot','replacechildren');
for k = 1:nFrames
surf(sin(2*pi*k/20)*Z,Z)
mov(k) = getframe(gcf);
end
% Create AVI file.
movie2avi(mov, 'myPeaks.avi', 'compression', 'None');
I understand this example and that I should have no compression to load into PowerPoint. However I dont understand how to properly preallocate my memory using struct.
回答1:
You don't need to pre-allocate. Just initialize mov = []
. Also getframe
assumes gcf
, so you can just use mov(k) = getframe()
. I agree that you want an uncompressed video. The codecs that come with Matlab are pretty limited. You could use an open source tool to compress the video if space is important.
回答2:
You could use avifile
to create the movie or even the newer VideoWriter
:
avifile
Z = peaks; surf(Z);
axis tight
set(gca,'nextplot','replacechildren');
vid = avifile('myPeaks.avi', 'fps',15, 'quality',100);
for k = 1:20
surf(sin(2*pi*k/20)*Z,Z)
vid = addframe(vid, getframe(gcf));
end
vid = close(vid);
winopen('myPeaks.avi')
VideoWriter
Z = peaks; surf(Z);
axis tight
set(gca,'nextplot','replacechildren');
vid = VideoWriter('myPeaks2.avi');
vid.Quality = 100;
vid.FrameRate = 15;
open(vid);
for k = 1:20
surf(sin(2*pi*k/20)*Z,Z)
writeVideo(vid, getframe(gcf));
end
close(vid);
winopen('myPeaks2.avi')
回答3:
You don't have to pre-allocate. It used to help to pre-allocate using moviein command, but it no longer provides any performance improvements. Here is the quote from MATLAB:
>> help moviein
moviein Initialize movie frame memory.
moviein is no longer needed as of MATLAB Release 11 (5.3).
In previous revisions, pre-allocating a movie increased
performance, but there is no longer a need to pre-allocate
movies. To create a movie, use something like the
following example:
for j=1:n
plot_command
M(j) = getframe;
end
movie(M)
For code that is compatible with all versions of MATLAB,
including versions before Release 11 (5.3), use:
M = moviein(n);
for j=1:n
plot_command
M(:,j) = getframe;
end
movie(M)
See also movie, getframe.
来源:https://stackoverflow.com/questions/8022758/matlab-how-to-preallocate-for-frames-to-make-a-movie