% m-file to test motion estimator for real-time compression project
% on using long-term memory MCP.  

frames = readFluoro('/user/julie/study02');
buffer_ims = readFluoro('/user/julie/study02_reconedbuffer');
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

% now have buffer of quantized images to feed to motion estimator
bufflen = 18;
blksize = 16;
ndispbits = 4;

% throw away first buffer because we used 2 buffer lengths to make the
% initial buffer instead of using intraframe coding.
frames = frames(:,:,bufflen+1:size(frames,3));

% test motion estimation with long-term buffer  
im = frames(:,:,19);
buffer = zeros(size(im,1),size(im,2),bufflen);
for j = 1:bufflen,
  buffer(:,:,j) = buffer_ims(:,:,19-j);
end
% get displacement vectors and error image:
[xd, yd, td, errim] = blockMatch(im, buffer, blksize, ndispbits);
nbits = 3;
numblocks = size(im,1)/blksize;
% quantize the error image
[image_dct, dct_in_columns] = getBlockDCT(errim,blksize);
dct_col_quant = quantizeDCTrows(dct_in_columns,nbits);
q_errim = reconFromDCTinRows(dct_col_quant,blksize,numblocks,numblocks);
% reconstruct the image frame from quantized error
r_im = decodeErr(q_errim,buffer,xd,yd,td,blksize);

figure
subplot(121)
dispim01(r_im);
hold on;
quiver(8:16:128,8:16:128,flipud(xd),flipud(-yd));

% test if bufflen of 1 is used:
buf = buffer_ims(:,:,bufflen);
[xd1, yd1, td1, errim1] = blockMatch(im, buf, blksize, ndispbits);
[image_dct, dct_in_columns1]  = getBlockDCT(errim1,blksize);
dct_col_quant1 = quantizeDCTrows(dct_in_columns1,nbits);
q_errim1 = reconFromDCTinRows(dct_col_quant1,blksize,numblocks,numblocks);
r_im1 = decodeErr(q_errim1,buf,xd1,yd1,td1,blksize);

subplot(122)
dispim01(r_im1);
hold on;
quiver(8:16:128,8:16:128,flipud(xd1),flipud(-yd1));

% create a gridded image to write td on top of:
figure
grid_im = r_im;
grid_im(blksize/2:blksize:128,:) = 255/2;
grid_im(:,blksize/2:blksize:128) = 255/2;
dispim01(grid_im)

% mesh the error images:
figure; subplot(121)
mesh(errim);
subplot(122)
mesh(errim1);

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
