Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

im trying to make this code to work as a bacground subtraction for motion detect

ID: 3820704 • Letter: I

Question

im trying to make this code to work as a bacground subtraction for motion detection in matlab but it only reads the first frame and make it grayscale and put up a difference between the same frame. can someone please help me loop it in away that it would go through all the frames thankyou!

v = VideoReader('IMG_6976.m4v');
NumOfFrames = v.NumberOfFrames;
vidHeight = v.Height;
vidWidth = v.Width;
vidResize = zeros(vidHeight, vidWidth);

FirstFrame = read(v,1);
bg_bw = rgb2gray(FirstFrame);
info = get(v);


for ii = 1:v.NumberOfFrames
%fr = read(v, [1 Inf]);
fr = read(v, ii);
fr_bw = rgb2gray(fr);
  
OptimalThreshold = 25;
  
absdiff = abs(double(fr_bw) - double(bg_bw));
  
for j=1:vidWidth   
for k=1:vidHeight
if ((absdiff(k,j) > OptimalThreshold))
vidResize(k,j) = fr_bw(k,j);
else
vidResize(k,j) = 0;
end
end
end

end
bg_bw = fr_bw;
figure(1),subplot(3,1,1),imshow(fr)
subplot(3,1,2),imshow(fr_bw)
subplot(3,1,3),imshow(uint8(vidResize))

Explanation / Answer

I think you are getting number of frames count value from video element... Here is the fix for the above problem..

v = VideoReader('IMG_6976.m4v');
NumOfFrames = 0;
% this will give exact count of frames...
while hasFrame(v)
   readFrame(v);
   NumOfFrames = NumOfFrames + 1;
end

vidHeight = v.Height;
vidWidth = v.Width;
vidResize = zeros(vidHeight, vidWidth);
FirstFrame = read(v,1);
bg_bw = rgb2gray(FirstFrame);
info = get(v);

%here frames will be considered and converted to black grey
for ii = 1:v.NumberOfFrames
%fr = read(v, [1 Inf]);
fr = read(v, ii);
fr_bw = rgb2gray(fr);
  
OptimalThreshold = 25;
  
absdiff = abs(double(fr_bw) - double(bg_bw));
  
for j=1:vidWidth   
for k=1:vidHeight
if ((absdiff(k,j) > OptimalThreshold))
vidResize(k,j) = fr_bw(k,j);
else
vidResize(k,j) = 0;
end
end
end

end
bg_bw = fr_bw;
figure(1),subplot(3,1,1),imshow(fr)
subplot(3,1,2),imshow(fr_bw)
subplot(3,1,3),imshow(uint8(vidResize))