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,:);
      
      I(k).cdata = rgb2gray(mov(k).cdata);
      t(k)=graythresh(I(k).cdata);

      [r,c] = size(I(k).cdata);
      n(k) = 0;
      for i = 1:r;
          for j = 1:c
              if I(k).cdata(i,j)>=t*255
                 n = n+1;
              end
          end
      end

      bw(k).cadata = im2bw(I(k).cdata, t(k));
      IC(k) = n(k)/(r*c-r2*c2);
      
end
 
k = 1 : numFrames;
figure;plot(k,IC(k));
xlabel('Time');
ylabel('IC');

% figure,imshow(bw(100).cadata);

%%

figure;
for k = 1 : numFrames
    imshow(bw(k).cadata);
    M(k) = getframe;
end

movie2avi(M,'otsu.avi','FPS',12);


%%

% cola=0:1/255:1;
% cola=[cola;cola;cola];
% cola=cola';
% aviobj.colormap=cola;
% 
% aviobj = avifile('Otsu.avi');
% for k = 1 : numFrames
% %     adata = bw(k).cadata
%    aviobj = addframe(aviobj,(bw(k).cadata)/256);
% end
% aviobj = close(aviobj);



