MATLAB: How to select region of interest in a video that works inside a loop

region of interest

I have tried several codes for region of interest but every code fails to work inside a loop. The codes I have tried, shows the same cropped frame for the entire video while working in a loop, rather than showing the other frames. I am finding a way to to select a region for the first frame so that the created position will be same for other frames also. One of the codes i tried is attached here:
vid=VideoReader('respiration.mp4');
fps= vid.FrameRate;
nof= vid.NumberOfFrames;
for k=1:nof;
img=read(vid,k);
if k==1
h=imrect;
position=wait(h);
I=imcrop(img,position);
end
I= I+1/fps;
end

Best Answer

  • vid=VideoReader('respiration.mp4');
    fps= vid.FrameRate;
    nof= vid.NumberOfFrames;
    for k=1:nof;
    img=read(vid,k);
    if k==1
    h=imrect;
    position=wait(h);
    [I, rect] = imcrop(img);
    else
    I = imcrop(img,rect) ;
    end
    end