如何在循环中使用 subplot、imshow 或 figure 来显示所有图像?

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

基本上,我想遍历所有视频帧,从背景图像中减去每一帧并显示结果,即 subtractedImg 使用子图或图形。

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; 

这里有问题 我在这里使用的子图,在这个循环中不显示输出。只显示一张图,标题为"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');

如何使用子图显示每个图像?例如使用 5x5 子图,如果我想显示 25 个减影图像,为什么 subplot(5,5,i),imshow(subtractedImg); 不起作用?

这应该为每一帧制作一个图形和一个新的子图:

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

这里要做的第一件事是删除循环内对 figure 的调用。在循环之前只调用一次图形就可以了。您可以在每次迭代时使用 clf 来清除当前图形的内容。

然后,您可能希望在 plot 命令之后添加一个 drawnow 命令以在每次迭代时刷新图形。

最后,您可能(或不想)添加一个 pause 以在帧之间等待用户输入。请注意,如果您使用 pause,则不需要 drawnow