I am trying to create a movie from my MATLAB plot. When I call getframe, it "usually" captures the plot image, but sometimes if there is something else active on the screen (which is normal if I continue to use the computer) it captures whatever window is active. Is there another way to grab the image of the active figure?
e.g.
fig = figure;
aviobj = avifile('sample.avi','compression','None');
for i=1:t
clf(fig);
plot(...); % some arbitrary plotting
hold on;
plot(...); % some other arbitrary plotting
axis([0 50 0 50]);
aviobj = addframe(aviobj, getframe(fig));
end
aviobj = close(aviobj);
OK, found the solution; instead of
sending the figure handle directly to addframe is enough:
As someone has already stated you don't have to use getframe, however if you insist on using it you can use
and this should fix your issue.
The Matlab people are apparently phasing out the avifile and addframe functions in future releases, replacing them with VideoWriter and writeVideo respectively. Unfortunately, this means that the accepted answer will no longer work, since writeVideo doesn't accept the figure handle as the argument.
I've played around with it a bit, and for future reference, the same thing can be accomplished using the undocumented hardcopy function. The following code works perfectly for me, with the added benefit of not even having a plot window pop up, so it does everything completely in the background:
I may depend on the renderer you're using. If it's
'painters'
, then you should be OK, but if it's anything else, such as'OpenGL'
, then I think it has to get the frame data from the graphics card, which means that if you have something overlapping the window, then that may end up in the output ofgetframe
.You can pass the handle of the desired figure or axis to GETFRAME to ensure that it doesn't capture another window.
If you use
getframe
in many subplots, try to add at the end: I think the get frame works fine it just the rendering a bit was unpositioned.