

clear

% ask user for image 
in1 = input('Input image:\n','s');
in2 = input('Background number:\n   1. Savanna (Dirt)\n   2. Desert (Carpet)\n   3. Grid (Brick)\n','s');

in_im=['proj2_imag/', in1];
im=imread(in_im);
bkg_num=str2num(in2);

final_imag=zeros(size(im));  % allocate for the final image
final_imag2=im;
%figure; imagesc(im); colormap(gray)

% threshold
upper=256;
if( bkg_num==1 )
  lower=240; % for Dirt images
else
  lower=150; % for Duncan and Brick images 
end
y = im<=upper & im>=lower;
%figure; imagesc(y); colormap(gray)

% clean the image
SE2=ones(4,2);
ero=erode(im,SE2);
SE=ones(4,4);
dil=dilate(ero, SE);
y=dil<=upper & dil>=lower;

% convert it to a format matlab can deal with
img=zeros(size(y));
img(:,:)=y(:,:);
G1=img*200;



G2=erode(G1,ones(1,20));
%figure; imagesc(G2); colormap(gray); title('G2'); grid on
G2a=dilate(G2,ones(1,30));
%figure; imagesc(G2a); colormap(gray); title('G2a'); grid on

G2b=erode(G1,ones(20,1));
%figure; imagesc(G2b); colormap(gray); title('G2b'); grid on
G2c=dilate(G2b,ones(30,1));
%figure; imagesc(G2c); colormap(gray); title('G2c'); grid on



Gv=zeros(size(G2a));
Gv(:,:)=G2a(:,:);
Gh=zeros(size(G2c));
Gh(:,:)=G2c(:,:);
G2d=Gh+Gv;
c=find( G2d<300 );
G2d(c)=0;
G2=zeros(size(G1));
G2(66:414,66:575)=G2d(66:414,66:575);
figure; imagesc(G2); colormap(gray); title('G2'); grid on


% find each object in the image
G3=G2;
while( sum(sum(G2)) ~= 0 )
  % column
  ri=sum(G2);
  f1=find(ri ~= 0);
  f2=find(ri == 0);
  c1=f1(1)-1;
  ctmp=find(f2>c1); c2=f2(ctmp(1));
  M1=G2(:,c1:c2);

  % row
  RI=sum(M1');
  F1=find(RI ~= 0);
  F2=find(RI == 0);
  C1=F1(1)-1;
  CTMP=find(F2>C1);
  C2=F2(CTMP(1));
  M2=M1(C1:C2,:);



  % determine if the object is a rectangle
  sizeM2=size(M2);
  if( (sizeM2(1)>23) & (sizeM2(2)>23) ) 
    s=(sum(sum(M2)))/200
    if( (s<2000) & (s>900) )
      isTank = rect_test(M2);
      if( isTank == 1 )

        figure; imagesc(M2); title('M2'); colormap(gray);

	% try to only get the white area of the tank
	rri=sum(M2);
	ff1=find(rri ~= 0);
  	ff2=find(rri == 0);
	cc1=ff1(1)-1;
	cctmp=find(ff2>cc1); cc2=ff2(cctmp(1));
  	MM1=M2(:,cc1:cc2);
	RRI=sum(MM1');
  	FF1=find(RRI ~= 0);
  	FF2=find(RRI == 0);
  	CC1=FF1(1)-1;
  	CCTMP=find(FF2>CC1);
  	CC2=FF2(CCTMP(1));
  	MM2=MM1(CC1:CC2,:);
	% get the coordinates
        r=round((2*C1+2*CC1+CC2)/2);
        c=round((2*c1+2*cc1+cc2)/2);
        final_imag2(r-7:r+7,c-7:c+7)=0;
      end % 3rd if
    end % 2nd if
  end % 1st if




  G2(C1:C2,c1:c2)=0;
end % while

figure; imagesc(final_imag2); title('Result'); colormap(gray);