%% 
clear
close all

% Last time we saved our image as a .tiff stack.  Reading in a tiff stack
% is very similar to reading in multi images.  First we load in a single
% image

img = im2double(imread('test_stack.tif'));
nframes = 10; % I know this from before

% Note, this only read in the FIRST frame.  To load in the rest, we have to
% run a for loop, similar to before.  We have to add a second argument to
% the imread, which will be the frame we want to load in.

for j = 2:nframes
    img(:,:,j) = im2double(imread('test_stack.tif',j));
end

%% Manipulating data
% An easy thing to do is take the mean along time.  Using the mean
% function, you have to tell it which dimension you want to average.

imgMean = mean(img,3);

figure
imshow(im2double(imgMean),[])


% We can also look to see movement by subtracting each previous frame.

for j = 1:nframes - 1 % Note, a difference image will always have 1 less frame
    diffimg(:,:,j) = img(:,:,j+1) - img(:,:,j);
end

% Display the difference movie
figure
for j = 1:nframes-1
    imshow(diffimg(:,:,j),[-.2 .2])
    pause(.5)
end

% Another common trick is to display the max intensity projecting at each pixel
maxImg = min(img,[],3); % Note, you have to add the brackets, and then the dimension

figure
imshow(maxImg)


% We might also ask what is the average value of each frame.  This will
% involve taking the mean across x and y.  X and Y are the first and second
% dimensions, so we have to take the mean twice across each of those
% dimensions.

trace_avg = mean(mean(img(51:60,81:100,:),2),1);

% Now we can try to plot this to see how the average intenisty changes

figure
plot(trace_avg)

% It throws an error.  The answer has to do with the size.
size(trace_avg)

% The mean command leaves the x and y dimensions, but can't plot on the
% third dimension.  The answer is to squeeze (get rid of dimensions size
% 1).

trace_avg2 = squeeze(trace_avg);
size(trace_avg2)

figure
plot(trace_avg2)

%%
