How to select specific frames (ex. every 10th frame) out of a video for further analysis?

25 views (last 30 days)
I have an .avi video file with ca. 300,000 frames (7 FPS) and I would like to analyze every nth frame (for example, frame 1, 10, 20, 30, 40, etc.).
I have successfully uploaded the file in clusters of 1000 frames and the analysis (image tracking) works well if I include every video frame. But I cannot seem to get MatLab to loop through every nth frame.
I tried something like this:
FishVid = VideoReader('MP02a.avi')
VidInfo=get(FishVid);
numberOfFrames = FishVid.NumberOfFrames
vidHeight = FishVid.Height;
vidWidth = FishVid.Width;
i= 1;
while i<= numberOfFrames
currentFrame= read(VidInfo,i);
combinedString=strcat(int2str(i-1),'.jpg');
imwrite(i,combinedString);
i=i+700;
end
BUT, this 1. saves each frame but doesn't concatenate them for further analysis and 2. in its current form, just gives me blank .jpg images.
Any suggestions on how to do this? Thanks!

Accepted Answer

Geoff Hayes
Geoff Hayes on 7 Apr 2015
Rebecca - look closely at the line where you write the image to file
imwrite(i,combinedString);
The code is writing out the integer i to the file named by combinedString whereas you want to write the frame to file instead
imwrite(currentFrame,combinedString);
Do this and you should have non-blank images.
If you want to concatenate all images together, then you can continue as you are doing above and just save each frame, the currentFrame variable, to a matrix or cell array.Something like
% determine which frames are going to be read
framesToRead = 1:700:numberOfFrames;
% initialize a matrix for all frames to be read
allFrames = zeros(vidHeight, vidWidth, 3, length(framesToRead));
% read in the frames
for k=1:length(framesToRead)
frameIdx = framesToRead(k);
currentFrame = read(FishVid,frameIdx);
combinedString = sprintf('%d.jpg',k-1);
imwrite(currentFrame,combinedString);
if k==1
% cast the all frames matrix appropriately
allFrames = cast(allFrames, class(currentFrame));
end
allFrames(:,:,:,k) = currentFrame;
end
Note how we cast allFrames to be of the same datatype as the video frames (this only occurs the once, for k identical to one).
Try the above and see what happens!

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!