MATLAB: Problem when using for-each loops for Image Segmentation

for loopfor loop to check all pixelimage segmentationMATLAB

Hi everyone
this following code is working good
clear
close all
v = VideoReader(fullfile('videos', 'combineSilver.mp4'));
s = VideoReader(fullfile('videos','scene.mp4'));
video=zeros(v.Height,v.Width,3,floor(v.Duration/(1/v.FrameRate))-2,'uint8');
t=1;%*



threshold = 0.6 ;
values=[0;1;0];
while hasFrame(v)
Img = im2double(readFrame(v));
mask = sqrt((values(1)-Img(:, :, 1)).^2+(values(2)-Img(:, :, 2)).^2+(values(3)-Img(:, :, 3)).^2)<threshold;
video(:,:,:,t) = imoverlay(im2uint8(Img),mask,[0 0 0]);
imshow(video(:,:,:,t));
t=t+1;%*
end
videoOut = VideoWriter('result.mp4','MPEG-4');
videoOut.FrameRate=v.FrameRate;
open(videoOut);
moveX=0;
for t=1:1:size(video,4)
im = video(:,:,:,t);
mask = im(:,:,1)+im(:,:,2)+im(:,:,3)==0;
frame=imoverlay(readFrame(s),~mask,[0 0 0]);
frame=frame+im;
writeVideo(videoOut,frame);
imshow(frame);
end
close(videoOut);
and my task is replace below rows with 2 for-loops
mask = sqrt((values(1)-Img(:, :, 1)).^2+(values(2)-Img(:, :, 2)).^2+(values(3)-Img(:, :, 3)).^2)<threshold;
video(:,:,:,t) = imoverlay(im2uint8(Img),mask,[0 0 0]);
Here is my new code with 2 for-loops
clear
close all
v = VideoReader(fullfile('videos', 'combineSilver.mp4'));
s = VideoReader(fullfile('videos','scene.mp4'));
video=zeros(v.Height,v.Width,3,floor(v.Duration/(1/v.FrameRate))-2,'uint8');
t=1;%*
threshold = 0.69 ;
values=[0;1;0];
while hasFrame(v)
Img = im2double(readFrame(v));
for i=1:1:size(Img,1)
for j=1:1:size(Img,2)
if(sqrt((values(1)-Img(i,j,1)).^2+(values(2)-Img(i,j,2)).^2+(values(3)-Img(i,j,3)).^2)<threshold)
mask=1;
else
mask=0;
end
video(i,j,:,t) = imoverlay(im2uint8(Img),mask,[0 0 0]);
end
end
imshow(video(:,:,:,t));
t=t+1;%*
end
videoOut = VideoWriter('result.mp4','MPEG-4');
videoOut.FrameRate=v.FrameRate;
open(videoOut);
moveX=0;
for t=1:1:size(video,4)
im = video(:,:,:,t);
mask = im(:,:,1)+im(:,:,2)+im(:,:,3)==0;
frame=imoverlay(readFrame(s),~mask,[0 0 0]);
frame=frame+im;
writeVideo(videoOut,frame);
imshow(frame);
end
close(videoOut);
but there are errors
Error using imoverlay (line 43)
A and BW must have the same number of rows and columns.
Error in forBackgroundRemoval (line 19)
video(i,j,:,t) = imoverlay(im2uint8(Img),mask,[0 0 0]);
Could you please see my code and give me some hints ?
Thanks for any helps

Best Answer

video(i,j,:,t) = imoverlay(im2uint8(Img),mask,[0 0 0]);
The error are self explaining, im2uint8(Img) and mask must have same sizes to avoid that error, please check it carefully