Mostafiz
Mostafiz

Reputation: 1687

reading and displaying video file frame by frame

I am newly working with Matlab. I want to read a video file and do some calculations every frame and display every frame. I wrote the following code but every time it only displays the first frame. can anybody please help.

mov=VideoReader('c:\vid\Akiyo.mp4');
nFrames=mov.NumberOfFrames;
for i=1:nFrames
  videoFrame=read(mov,i);
  imshow(videoFrame);

end

Upvotes: 5

Views: 38785

Answers (4)

kara
kara

Reputation: 1

*=I was making a function to play any .avi file as a set of frames in a figure. Here's what a did. A bit of a combo of what you've done, except my NumberOfFrames wasn't working: (noteL this also shows it in colour)

function play_video(filename)
% play_video  Play a video file
% play_video(filename) plays the video file specified by filename in a MATLAB Figure window.

figure
set(figure, 'Visible', 'on')
mov=VideoReader(filename);
vidFrames=read(mov);
duration = mov.Duration;
frame_rate = mov.FrameRate;
total_frames = duration .* frame_rate


for i=1:1:total_frames
   imshow(vidFrames(:, :, :, i), []);
   drawnow
end

Upvotes: 0

Artem Lenskiy
Artem Lenskiy

Reputation: 43

Function read() and the field NumberOfFrames() are now deprecated, Matlab suggests using

xyloObj = VideoReader(file);
vidHeight = xyloObj.Height;
vidWidth = xyloObj.Width;
mov = struct('cdata',zeros(vidHeight, vidWidth, 3,'uint8'), 'colormap',[]);

while hasFrame(xyloObj)
    mov(k).cdata = readFrame(xyloObj,'native');     
end

In case you want to estimate a number of frames in the video, use nFrames = floor(xyloObj.Duration) * floor(xyloObj.FrameRate);

Upvotes: 1

Khatri
Khatri

Reputation: 646

Below suggested code is showing only one frame

imshow(vidFrames(:,:,i),[]);

I am doing following things to store each frame

obj = VideoReader('path/to/video/file');

for img = 1:obj.NumberOfFrames;
    filename = strcat('frame',num2str(img),'.jpg');
    b = read(obj,img);
    imwrite(b,filename);
end

This will store all the frames in your home directory.And yes, as also suggested by Vivek and Parag

You need to use VideoReader as mmreader has been discontinued by MATLAB.

Upvotes: 0

Autonomous
Autonomous

Reputation: 9075

Note: mmreader API has been discontinued by MATLAB so prefer using VideoReader.

See comment by @Vivek.

I usually do this:

obj=mmreader('c:\vid\Akiyo.mp4');
nFrames=obj.NumberOfFrames;
for k=1:nFrames
    img=read(obj,k);
    figure(1),imshow(img,[]);
end

As far as your code is concerned, I saw MATLAB's documentation. You should do the things in following order:

mov=VideoReader('c:\vid\Akiyo.mp4');
vidFrames=read(mov);
nFrames=mov.NumberOfFrames;
for i=1:nFrames
   imshow(vidFrames(:,:,i),[]);  %frames are grayscale
end

Upvotes: 10

Related Questions