Extract foreground object from background

9 views (last 30 days)
harneet chugga
harneet chugga on 11 Feb 2016
Edited: Image Analyst on 11 Feb 2016
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
Image Analyst
Image Analyst on 11 Feb 2016
You forgot to attach the images, and to read this and this.
Matt J
Matt J on 11 Feb 2016
I have marked up your code for you (just this once) to make it more readable.

Sign in to comment.

Answers (1)

Image Analyst
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.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!