clear all; 
close all;

colormap('gray');
map=colormap;

% Construct a multimedia reader object associated with file 'filename.avi' 
readerobj = mmreader('Filename.avi');
      
% Read all video frames.

numFrames=175; 
vidFrames = read(readerobj, [1 175]);
 
% Convert to BW
for i=1:numFrames
    image=ind2gray(vidFrames(:,:,:,i), map); 
    bw(:,:,i) = im2bw(image,0.111);
end
clear vidFrames;

% Transform BW images into a binary arrays 

for i=1:size(bw,1)
    for j=1:size(bw,2)
    if bw(i,j,1)>0
        bw_output(i,j)=1;
    else bw_output(i,j)=0;
    end
    end
end    
        
picturetopresent=bw_output(1:475,20:370,1);
figure;
imshow(picturetopresent)


ROI=bw(1:475,1:475,:);

% Use the regionprops function to find the centroid 

for k=1:numFrames;
positions= regionprops(ROI(:,:,k), 'Centroid');
area=regionprops(ROI(:,:,k), 'EquivDiameter');
    for i=1:length(positions)
        x(i,k)=positions(i,1).Centroid(1);
        y(i,k)=positions(i,1).Centroid(2);
        diam(i)=area(i).EquivDiameter;
    end
    thresh=1;

    j=0;
    for i=1:length(positions)
        if diam(i)>thresh
            j=j+1;
            X(j,k)=x(i,k);
            Y(j,k)=y(i,k);
        end
    end
end
num_part=j;


% Find NPs in different scans
for j=1:num_part
    label(j,1)=j;
    for k=1:numFrames-1
         distance=((X(label(j,k),k)-X(:,k+1)).^2)+((Y(label(j,k),k)-Y(:,k+1)).^2);
        label(j,k+1)=find(min(distance)==distance,1);
    end
end

close;
figure; imshow(ROI(:,:,1));
colorbar;
hold on;

for particle=1:num_part
    for k=1:numFrames
        plot(X(label(particle,k),k), Y(label(particle,k),k),'g');
    end
end


time=0:0.2667:(numFrames-1)*0.2667;

for i=1:num_part
    for k=1:numFrames
        radius(i,k)=sqrt((X(label(i,k),k)-X(label(i,1),1))^2+(Y(label(i,k),k)-Y(label(i,1),1))^2);
        angle_r(i,k)=asind((Y(label(i,k),k)-Y(label(i,1),1))/radius(i,k));
 
       
        baseline(i,k)=0;%8.5*k/numFrames; 
        displacement(i,k)=radius(i,k)-baseline(i,k);
    end

    grid on;
end
