tic
close all
clear all
clc
%load and separate the three channels
GorskiiImage=(imread('./results/00889u.tif'));
% GorskiiImage=(imread('01044v.jpg'));
[ height ,width]=size(GorskiiImage);
 
 height=height/3;
B=GorskiiImage(1:height,:);
G=GorskiiImage( height + 1:2*height,:);
R=GorskiiImage( 2*height+1:end,:);
 
colorImage1=cat(3,R,G,B);
dsampleFlag=0;
figure
imshow(colorImage1);


% downsample large images
if(height> 512 && width>512 )
    factor= 512/width;
    colorImage=imresize(colorImage1,factor,'bilinear');
    dsampleFlag=1;
else 
    colorImage=colorImage1;
    factor=1;
end

%keep search area large and do first coarse alignment
 disp=10;
 % anchor is required shift
 anchor=zeros(1,2,2);
  [ nccMap,anchor ] = shiftAlign(colorImage,disp,anchor,1); 
  shift= disp+1;
colorImage(shift:end-anchor(1,1,1),shift:end-anchor(1,2,1),1)=colorImage(shift+anchor(1,1,1):end,shift+anchor(1,2,1):end,1);
colorImage(shift:end-anchor(1,1,2),shift:end-anchor(1,2,2),2)=colorImage(shift+anchor(1,1,2):end,shift+anchor(1,2,2):end,2);
 
  figure
 imshow(uint8(colorImage));

  figure
    imagesc(nccMap(:,:,1));
    colormap jet
 
%traverse through the image pyramid for finer aligment
 if(dsampleFlag==1)
      kprev=factor;
 anchorNew=0*anchor;
    
     
     
     for k=[0.5,1]
         dispFine=ceil(k/kprev)+2 ; % only +1 is needed, +2 is precautionary
 nccMap=zeros(2*dispFine+1,2*dispFine+1);
 anchor=ceil((k/kprev)*anchor)+anchorNew;    
     [ nccMap,anchorNew ] = shiftAlign(imresize(colorImage1,k,'bilinear'),dispFine,anchor,k);
 
kprev=k;
    figure
    imagesc(nccMap(:,:,1));
    colormap jet
     end
     anchor=anchor+anchorNew; 
    % shift the images according to value of anchor
shift=ceil((1/factor)*(disp+1))+dispFine+1;
colorImage1(shift:end-anchor(1,1,1),shift:end-anchor(1,2,1),1)=colorImage1(shift+anchor(1,1,1):end,shift+anchor(1,2,1):end,1);
colorImage1(shift:end-anchor(1,1,2),shift:end-anchor(1,2,2),2)=colorImage1(shift+anchor(1,1,2):end,shift+anchor(1,2,2):end,2);
figure
imshow(uint8(colorImage1));

    else
     colorImage1=colorImage;
 end
 
    %search for small rotations, angRot is value of rotation needed
  [angRot] = rotate(colorImage1,dsampleFlag); 
  
  % rotate the image
colorImage1(:,:,1)=imrotate(colorImage1( :,:,1),angRot(1),'nearest','crop');
colorImage1(:,:,2)=imrotate(colorImage1( :,:,2),angRot(2),'nearest','crop');
 
 figure
 imshow(uint8(colorImage1));
 
 % find sub-pixel shift
   [sPixI, sPixJ] = sPix(colorImage1,dsampleFlag );
 
   % align the images using above sub-pixel shifts
  colorImage1(:,:,1)=conv2(conv2(colorImage1(:,:,1),sPixJ(:,:,1),'same'),    sPixI(:,:,1),'same');
  colorImage1(:,:,2)=conv2(conv2(colorImage1(:,:,2),sPixJ(:,:,2),'same'),    sPixI(:,:,2),'same');
     
 
 figure
 imshow(uint8(colorImage1));
 toc
  
