MATLAB: How to merge video files without crashing the memory

create moviesvideo processing

I am trying to create a program that randomly chooses two seconds from a variable number of relatively short movie clips (short videos created for the purpose of putting together a '2 seconds a day' type movie). Everything is working fine, but I crash my systems memory after 8 videos or so, and I'm trying to put together around 100. I'm just learning how to program and my main problem revolves around how to free up memory. Below is my code.
if true
% code
files = dir( 'C:/Users/psychuser/Desktop/Pictures and Misc/Phone/*.mov' ); %finds all movies in a certain folder
n = 1;
for i= 1 : size( files , 1 );
originalfilename = sprintf( 'C:/Users/psychuser/Desktop/Pictures and Misc/Phone/%s' , files(i,1).name );%creates variable file name
obj = VideoReader( originalfilename ); %turns video into variable 'obj'
video = obj.read; %read video and properties into matlab file
x = round( obj.FrameRate ); %from that properties file turn framerate of video into variable
y = obj.NumberOfFrames; %from that properties file turn total number of frames into variable
z = ( y - ( x * 2 ) ); %z subtracts the frame rate from the total number of frames so that the new movie doesn't exceed the total number of frames
if ( x * 2 ) <= y %if total number of seconds is greater than 2 seconds choose random two seconds
j = ( n : (n + ( x * 2 ))); %j is a counter that knows where the last video ended and how big the current video is
startframe = randi ( z ); %choose random start point between first frame and last possible frame
choicerng = ( startframe : ( startframe + ( x * 2 ) ) );
video1 ( : , : , : , j ) = video( : , : , : , choicerng ); %merge new video to old 'combined' video

else % else choose the whole video
j = ( n : ( ( y - 1 ) + n ) ); %Y is rounding up for these videos creating a problem with a less than two second clip, to resolve this i subtracted 1 frame, needs a better fix
choicerng = ( 1 : y ); % choose whole video
video1 ( : , : , : , j ) = video( : , : , : , choicerng ); %merge new video to old 'combined' video
end
n = max(j) + 1; % last frame in the combined video
clear x y z originalfilename obj video choicerng startframe %clear variables
end %everything below here writes out the video to a new file called twoseconds
newfilename = 'C:/Users/psychuser/Desktop/Pictures and Misc/ChristiPhone/TwoSecond/twoseconds.avi';
writeobj = VideoWriter( newfilename );
open( writeobj );
writeVideo( writeobj , video1 );
close( writeobj );
clear all
end

Best Answer

Try not reading the whole video into memory. Use read() to read just the frames you want in.
Related Question