Extract foreground object from background
9 views (last 30 days)
Show older comments
I have 2 images. One is background image and other image has same background but with some foreground object. I want to extract foreground object from background. Simple subtraction operation in matlab will not suffice as it sub
the code below does not give correct output
im1 = imread('foreground.jpg')
im2 = imread('background.jpg')
[m n k]=size(im2);
deltaImage = zeros(m,n,3);
fprintf('%d %d %d.\n',m,n,k);
for l=1:k
for i=1:m-1
for j=1:n-1
if im1(i:j:l)~=im2(i:j:l)
deltaImage(i,j,l) = im1(i,j,l);
end
end
end
end
imshow(deltaImage)
2 Comments
Answers (1)
Image Analyst
on 11 Feb 2016
Edited: Image Analyst
on 11 Feb 2016
This is nonsense: (i:j:l). It will work but doesn't do what you thought it would. It goes from i to l in steps of j and is a vector, not a set of 3-D indexes. You don't even need a loop. You can just do
[rows, columns, numberOfColorChannels] = size(im2);
fprintf('%d rows, %d columns, %d color channels.\n', rows, columns, numberOfColorChannels);
mask = im1 ~= im2;
deltaImage = zeros(rows, columns, numberOfColorChannels);
delta(mask) = im1(mask);
Even with that simplification, the code is not very robust and could be improved, for example to check that the dimensions are the same, to check that mask is not empty, checking for tolerance instead of equality, etc.
0 Comments
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!