clear
close all

% We start by loading in a tif stack of 250 images.
file_name = 'Yeast_movie.tif';
nframes = 250;

% Load in the first frame
img = imread(file_name);

% Load in the rest of the frames
for j = 2:nframes
    img(:,:,j) = imread(file_name,j);
end

% Convert to a double, like we always do.
imgDouble = im2double(img);

% Now lets play it to see what we have.  To play a movie, we have to set
% the contrast limits at the beginning.  To do that, we can use the (:)
% operator.

minVal = min(imgDouble(:)) % The : says take the minimum over all dimensions.
maxVal = .7*max(imgDouble(:)) % The 0.7 is just to make the contrast look better

% Now display the movie with the proper contrast values
figure
for j = 1:3:nframes
    imshow(cellImg(:,:,j),[minVal maxVal])
    title(['Frame: ' num2str(j) ' of ' num2str(nframes)])
    drawnow
end

% How can we quickly determine what a cell is doing.  We want to have the
% user select an ROI, and then determine the intensity across time for
% those pixels.  The command to have the user select is getrect.

% First create an average image in time.
avgimg = mean(imgDouble,3);

%%
figure
imshow(avgimg,[])

rectangle = uint16(getrect)

% Note that rect has [x start, y start, x length, y length]. We want to
% take the average image in ONLY that rectangle.  Make sure to squeeze to
% get rid of extra dimensions
cellImg = imgDouble(rectangle(2):rectangle(2)+rectangle(4), rectangle(1):rectangle(1)+rectangle(3), :);
cellTrace = squeeze(mean(mean(cellImg,2),1));

% You'll have to believe me that we took a frame every 4 seconds.
time = 4*(1:nframes);
figure
subplot(2,1,1)
imshow(mean(cellImg,3),[])
subplot(2,1,2)
plot(time,cellTrace)

%%
% How do we write a image stack to a movie that can be played on a computer
% First you create a writer object with a file name, and then open access
% to that memory
writerObj = VideoWriter('yeast_movie.avi');
open(writerObj);

% Now we run a for loop where we display the image, use getframe to send
% that to memory, and writeVideo to write that image to an avi file.
figure
for j = 1:nframes
    imshow(imgDouble(:,:,j),[minVal maxVal]);%
    title(num2str(j))
    text(8,8,[num2str(time(j)) ' s'],'Color',[1 1 1])
    frame = getframe;
    writeVideo(writerObj,frame);
end
close(writerObj);



