Search code examples
matlabmatlab-figurefiguresubplotimshow

How to use subplot, imshow, or figure in a loop, to show all the images?


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?


Solution

  • 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