aks
aks

Reputation: 43

Finding number of frames in a video

I tried to display a video frame by frame for which I need to know the total number of frames. But it shows an error: "unable to determine the number of frames in this file".

obj = VideoReader('a.avi');
nof=obj.NumberOfFrames;
for i=1:nof
    img = read(obj,i);
    imshow(img);

end

Upvotes: 4

Views: 7628

Answers (3)

aviimaging
aviimaging

Reputation: 167

Matlab will deprecate read() and NumberOfFrames in future versions. Below are some video open and find-number-of-frames function that I use to work through the Matlab version changes. I have tested a similar version of this on a few avi files, with required codecs installed.

function [totalFrames] = findNumFrames(videoSrcPath, SelectedReader)
    % open video source
    if ( SelectedReader == 1 )
            % VideoReader currently has a read to random frame but will be
            % deprecated soon                
            videoSrc = VideoReader(videoSrcPath); 
    elseif ( SelectedReader == 0 )
            %vision.VideoFileReader does not have a read to random frame
            videoSrc = vision.VideoFileReader(videoSrcPath,...
               'ImageColorSpace', 'Intensity'); 
    end

    % get number of frames
    if ( SelectedReader == 1 )
        % The below read() and NumberOfFrames will be deprecated in
        % future versions and we will have to use SelectReader == 0
        % or readFrame 
        try                    
            lastFrame = read(videoSrc, inf); % need to read last frame to get the number of frames
            totalFrames = videoSrc.NumberOfFrames;                    
        catch
            warning('Problem using read - possibly deprecated. Using readFrame instead.'); 
        end

    elseif ( SelectedReader == 0 )

        totalFrames = 0;
        while( ~isDone(videoSrc) )
            step(videoSrc);
            totalFrames = totalFrames + 1;
        end
        reset(videoSrc);

    end

end 

Upvotes: 0

Dula wnRp
Dula wnRp

Reputation: 163

vidFrames = read(readerobj);
numFrames = get(readerobj, ‘numberOfFrames’);

Upvotes: 0

VHarisop
VHarisop

Reputation: 2826

The video might be encoded with a variable frame rate, in which case MATLAB cannot detect the number of frames until it reads the last frame (as is documented here.

To find out, you should read the last frame, as suggested here.

Obj = VideoReader('varFrameRateFile.avi');
lastFrame = read(Obj, inf);
numFrames = Obj.NumberOfFrames;

Upvotes: 6

Related Questions