0
votes

Basically, I want to loop over all frames of video, subtract each frame from background image and display the result i.e subtractedImg either using subplot or figure.

vidObj = VideoReader('test3.mp4');
width = vidObj.Width;
height = vidObj.Height;

subtractedImg = zeros([width height 3]);
videoFrames = [];
k = 1;
while hasFrame(vidObj)
    f = readFrame(vidObj);
    f=uint8(f);
    videoFrames = cat(numel(size(f)) + 1, videoFrames, f);
    k = k+1;
end
backgroundImg = median(videoFrames,4);
i=1; 

Problem here subplot which I have used here, in this loop does not show output. Only one figure is displayed with title "last one".

while hasFrame(vidObj)
    frame = readFrame(vidObj);

    subtractedImg=imabsdiff(frame,backgroundImg);
    figure(i); imshow(subtractedImg);
    % subplot(5,5,i),imshow(subtractedImg); 
    %uncommenting above line does not work, subplot not shown
    if(i < 20)
    i= i+1;
    end

end %end while

subplot(1,2,1),imshow(subtractedImg),title('last one');

How do I show each image using subplot? For example using 5x5 subplot, If I want to display 25 subtracted images, why subplot(5,5,i),imshow(subtractedImg); is not working?

2

2 Answers

0
votes

This should make one figure and a new subplot for each frame:

figure(1);clf;
for ct = 1:size(videoFrames,4)        
    subtractedImg=imabsdiff(videoFrames(:,:,:,ct),backgroundImg);
    subplot(5,5,ct);imshow(subtractedImg); 
    if(ct == 25)
        break
    end
end
0
votes

The first thing to do here is to remove the call for figure inside the loop. Just one call to the figure before the loop is fine. You can use clf at each iteration to clear the current figure's content.

Then, you may want to add a drawnow command after the plot commands to refresh the figure at each iteration.

Finally, you may (or not) want to add a pause to wait for user input between frames. Note that if you use pause then drawnow is not required.