How to use the double function for background subtraction?

1 view (last 30 days)
I have a script that creates a "moving box" and I need to write my own background subtraction code to find the position of the box without using ginput. I know I can do this by subtracting the first image from each of the images and finding the areas of difference, but I'm not sure the code for that. Below is the code I'm working with. I've also uploaded it to GitHub here.
I've uploaded the moving box.mat file as well.
%this loads and runs the moving box video and then plots the path of it in
%another figure by using red circles.
load('movingbox (2).mat');
figure
gput=[];
for i=1:5,
BW=imagesc(mov(:,:,i));
colormap(gray);
title('pick centroid')
[xs,ys] = ginput(1);
pause(0.1);
hold on
gput=[gput ginput(1)];
end
figure
xlim([0 700])
ylim([0 700])
plot(gput,'ro','LineWidth',3,'MarkerSize',15)
camroll(90)
%this is the entire script I'm working on. I want to load the movie,
%subtract the background using the difference = line, and then plot the
%path of the box using the red circles.
load('movingbox (2).mat');
figure
for i=1:30,
BW=imagesc(mov(:,:,i));
colormap(gray);
pause(0.1);
hold on
end
difference = double(mov(:,:,frame x)) - double(mov(:,:,frame 1)) %this line must be used, in the for loop I believe
%the code below can be altered
% dataDir=load('movingbox (2).mat');
r=find(frames(dataDir));
frames=read(r,[1 300]);
pic=frames(:,:,1,1);
imagesc(pic);
threshs = 0.1:0.1:0.8;
for i =1:length(threshs)
pic = frames(:,:,1);
BW = im2bw(pic,threshs(i));
subplot(2,4,i);
imagesc(BW);
title(['frame ',num2str(i)]);
end
t = input('which threshold?');
BW = im2bw(BW,threshs(t));
BW = imcomplement(BW);
BW_select = bwselect(BW,xs,ys,8);
b = bwlabel(BW_select,8);
s = regionprops(b, 'Area','Orientation', 'MajorAxisLength', ...
'MinorAxisLength', 'Eccentricity', 'Centroid');
hold on
phi = linspace(0,2*pi,50);
cosphi = cos(phi);
sinphi = sin(phi);
for k = 1:length(s) %draw red outlines on all of the blobs
%finding where these are
xbar = s(k).Centroid(1);
ybar = s(k).Centroid(2);
a = s(k).MajorAxisLength/2;
b = s(k).MinorAxisLength/2;
%drawing ellipses
theta = pi*s(k).Orientation/180;
R = [ cos(theta) sin(theta)
-sin(theta) cos(theta)];
xy = [a*cosphi; b*sinphi];
xy = R*xy;
x = xy(1,:) + xbar;
y = xy(2,:) + ybar;
plot(x,y,'r','LineWidth',2);
hold on;
end

Accepted Answer

Image Analyst
Image Analyst on 14 Nov 2021
Try this:
load('movingbox (1).mat');
figure
frame1 = mov(:, :, 1);
for i=1:30
thisFrame = mov(:, :, i)
BW=imagesc(thisFrame);
colormap(gray);
drawnow;
pause(0.1)
hold on
difference = double(thisFrame) - double(frame1) % or can use imabsdiff(thisFrame, frame1)
% Now do something with difference....
end

More Answers (0)

Categories

Find more on Graphics Performance in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!