Search code examples
matlabvideoframe-rate

Accelerate framerate for figure update in MATLAB


I read in a video in MATLAB like this:

v = VideoReader('testvid.wmv')

cnt = 0;
while hasFrame(v)
    cnt = cnt + 1;
    video(cnt,:,:,:) = readFrame(v);
end

If I check out the video object, I tells me that the video is with 24 frames. However, If would show it directly after reading it (so basically imshow(readframe(v)) inside the for-loop it only gets shown with around 5 frames per second.

That's why I have written it like the code above, so that the frames are getting prestored into the workspace, and now I can show them like

figure
for i=1:cnt
   tic
   imshow(squeeze(video(i,:,:,:)))
   toc
end

However, I still get only 10 frames - is MATLAB limitied in this direction? Is there a better way to display a video with a fast enough framerate inside MATLAB?


Solution

  • You can update your plot CData rather than replotting it every time.

    % Prepare 24 fake RGB coloured frames
    A = randn(100,100,3,24);
    
    figure
    
    % Time the frame display time when replotting
    tic
    for k = 1 : 24
         h = imshow(A(:,:,:,k));
         drawnow
    end
    t = toc;
    disp(t / 24)
    
    
    % Time the frame display time when updating CData
    tic
    for k = 1 : 24
        if k == 1
            % Create the image object
            h = imshow(A(:,:,:,k));
        else
           % Update the Cdata property of image
           set(h , 'cdata' , A(:,:,:,k));
        end
        drawnow
    end
    t = toc;
    disp(t / 24)
    

    My output is:

    0.0854
    
    0.0093
    

    So I get a tenfold improvement when updating CData. This is actually faster than 24 frames per second!