1

I have code to capture the frames of a video. I need to put the first 20 frames in an array. How can I do that? Below is the code that I have:

filename = 'Wildlife.wmv';
mov = mmreader(filename);

% Output folder
outputFolder = fullfile(cd, 'frames');
if ~exist(outputFolder, 'dir')
   mkdir(outputFolder);
end

%getting no of frames

numberOfFrames = mov.NumberOfFrames;
numberOfFramesWritten = 0;

for frame = 1 :20
   thisFrame = read(mov, frame);
   outputBaseFileName = sprintf('%3.3d.bmp', frame);
   outputFullFileName = fullfile(outputFolder, outputBaseFileName);
   imwrite(thisFrame, outputFullFileName, 'bmp');
   progressIndication = sprintf('Wrote frame %4d of %d.', frame,numberOfFrames);
   disp(progressIndication);
   numberOfFramesWritten = numberOfFramesWritten + 1;
end

progressIndication = sprintf('Wrote %d frames to folder "%s"',numberOfFramesWritten,outputFolder);
disp(progressIndication);
rayryeng
  • 102,964
  • 22
  • 184
  • 193
salma_magdy
  • 13
  • 1
  • 4

1 Answers1

0

Simply place each frame into a 3D array, and return a stacked 3D array. As such, before your for loop, do this:

videoFrames = [];

Inside your for loop, after the read statement, do this:

videoFrames = cat(3,videoFrames,thisFrame);

The above case only covers grayscale images. For colour images, you'll need to create a 4D array, as the third dimension will be colour channels. In other words, do this:

videoFrames = cat(4,videoFrames,thisFrame);

To make this colour or grayscale agnostic, you can check to see how many dimensions are returned from the size method. size returns an N x 1 vector that contains the size of each dimension and N would be the total number of dimensions. This would be a 2 element array if it's a 2D array (grayscale) and a 3 element array if it's a 3D array (colour). As such, you could change the above two statements to a single one such that:

videoFrames = cat(numel(size(thisFrame)) + 1, videoFrames, thisFrame);

You simply count how many dimensions there are, and add 1 to stack in the next dimension.


If you want to access the ith frame, you can do:

frame = videoFrames(:,:,i); %// Grayscale
frame = videoFrames(:,:,:,i); %// Colour
rayryeng
  • 102,964
  • 22
  • 184
  • 193
  • You can initialize `videoFrames` to save some calculation time. `videoFrames = zeros([size(read(mov, 1)), 20])` and then store frames with `videoFrames(:,:,ii) = thisFrame;` (for grayscale). – Yvon Jul 26 '14 at 18:18
  • @Yvon - Thank you for the suggestion. I decided not to pre-allocate as the OP seems to be a new user of MATLAB. As such, I decided to go for readability and simple modifications to the established code in order to get things running. Though your suggestion is certainly valid, I decided not to do this for the sake of the OP. – rayryeng Jul 27 '14 at 03:26