clc; clear all;


%%
% Construct a multimedia reader object 
% readerobj = mmreader('dypic_05100_cam1_top.avi');
readerobj = VideoReader('dypic_05100_cam1_top.avi');
 
% Read in all video frames.
vidFrames = read(readerobj);
 
% Get the number of frames.
numFrames = get(readerobj, 'numberOfFrames');
 
% Create a MATLAB movie struct from the video frames.
for k = 1 : numFrames
      mov(k).cdata = vidFrames(:,:,:,k);
      
      x1=125; x2=521;
      y1=180; y2=400;

      x3=268; x4=380; y3=307;

      I1(k).cadata = mov(k).cdata(y1:y2,x1:x2,:);
      I2(k).cadata = mov(k).cdata(y3:y2,x3:x4,:);

      r2=y2-y3+1; c2=x4-x3+1;

      mov(k).cdata(y3:y2,x3:x4,:)=0;
      mov(k).cdata=mov(k).cdata(y1:y2,x1:x2,:);
      
      mov(k).cdata = rgb2gray(mov(k).cdata);
      
      im(k).cdata=im2double(mov(k).cdata);

      kms=2;

      ima(k).cdata=double(im(k).cdata);
      
      si=size(ima(k).cdata);
      
      ima(k).cdata=double(im(k).cdata(:));

      map1(k).cdata = kmeans(ima(k).cdata,kms, 'EmptyAction', 'singleton');
      mask(k).cdata = zeros(size(map1(k).cdata));

      for i = 1:kms
          s(i) = sum(sum(ima(k).cdata.*(map1(k).cdata==i)))/sum(sum(map1(k).cdata==i));
      end

      a(k) = find(s==max(s));
      p = find(map1(k).cdata==a(k)); 
      mask(k).cdata(p) = 1;

      IC(k) = length(p)/(si(1)*si(2)-r2*c2);

      mask1(k).cdata = uint8(mask(k).cdata*255);
      out(k).cdata = reshape(mask1(k).cdata,si(1),si(2));

      
end

 
%%
figure, 
k = 1 : numFrames;
plot(k,IC(k));
xlabel('Time');
ylabel('IC');


%%
figure,
for k = 1 : numFrames
    imshow(out(k).cdata);
    M(k) = getframe;
end

movie2avi(M,'05400_kmeans.avi','FPS',12);






